Java的运行

Java编译过程不生成机器语言,生成字节码。同时具备高级语言的可移植性。(一次编写到处运行)
Java创建了JVM(Java虚拟机),通过JVM支持字节码的解释运行。

Java程序的构成

  • 源代码文本文件:后缀为”.java”
  • 文件名:首字母大写,必须为英文,不能有空格
  • 代码示例:image.png

    变量

    为了存储数据,我们会先创建变量 例:

  • String say;

  • int age;

    方法

  • 随机数 Math.random() //double型的数据

Math.random()方法用于返回一个随机数,范围为【0.0,1.0】

  1. // 得到一个随机数
  2. double value = Math.random();
  3. System.out.println(value);
  • 类型转化

    int nValue =(int) value;

  • 如果想得到0~9之间的随机数,需要×10

    1. // (value*10) 用小括号包围是因为先乘10得到结果在转化为整数
    2. // 要不然得不到结果,这个就是数学的优先级
    3. int nValue = (int) (value*10);
  • 生成6位随机数时,有时生成的是0.011233…,×1000000之后我们发现有时只有5位,

于是我们可以将生成的随机数+1或者进行一些其他的操作,让最终的结果变成6位。

  1. public static void main(String[] args) {
  2. double value =Math.random();
  3. if(value<0.1){
  4. value=value+1;
  5. int code =(int)(value*100000);
  6. System.out.println(code);
  7. }else{
  8. int code =(int)(value*1000000);
  9. System.out.println(code);
  10. }

自定义方法

  • main()方法
    1. // public(公共的) static(静态) void(空类型)
    2. public static void 方法名称(方法参数){
    3. 代码块
    4. }

方法名遵守小驼峰命名法

  1. // 密码
  2. public static void password(){
  3. //代码块
  4. }
  5. // 我的文档
  6. public static void myDocument(){
  7. //代码块
  8. }

将上面的调用随机数方法写在自己定义的方法中,要用的时候直接调用random()就好了

  1. public class Custom {
  2. public static void main(String[] args) {
  3. random();
  4. }
  5. /**
  6. *生成6位随机数
  7. */
  8. public static void random(){
  9. int code = (int) ((Math.random()+1) * 100000);
  10. System.out.println(code);
  11. }
  12. }

方法参数

需要在定义方法的时候在括号中定义,这个变量的声明叫做形参
image.png

短信验证码例子最终版

  1. public class MessageCode1 {
  2. public static void code(int length,String text){
  3. int random=(int)((Math.random()*9+1)*length);
  4. System.out.print(text+"【"+random+"】");
  5. }
  6. public static void main(String args[]){
  7. String txt="你本次的验证码是";
  8. code(1000,txt);
  9. }
  10. }

for循环

  1. String[] tables = new String[3];
  2. tables[0] = "张三";
  3. tables[1] = "李四";
  4. tables[2] = "王五";
  5. for(int i = 0; i< tables.length;i++){
  6. String name = tables[i];
  7. System.out.println(name);
  8. }

我们在数据确定的情况下也可以写成下面这样,这段代码同时完成了数组长度的设定和数组的赋值

  1. public static void main(String[] args) {
  2. String[] tables = new String[]{"张三","李四", "王五"};
  3. for(int i = 0; i < tables.length; i++){
  4. String name = tables[i];
  5. System.out.println(i+":"+name);
  6. }
  7. }

另一种for循环

  1. for(String name : tables){
  2. }
  3. //上面的循环和下面的是同一个意思
  4. for(int i = 0; i < tables.length; i++){
  5. String name = tables[i];
  6. }

字符串长度

  1. String message = "今天我在学习 Java 字符串";
  2. int size = message.length();
  3. System.out.println(size);

验证消息长度封装为方法

  1. public class Test71 {
  2. public static void main(String[] args) {
  3. boolean countPass = validateCount("今天天气挺好的");
  4. System.out.println(countPass);
  5. }
  6. public static boolean validateCount(String message){
  7. if(message.length()>140){
  8. return false;
  9. }
  10. return true;mess
  11. }
  12. }

取出字符串中的某个字

  1. public static void main(String[] args) {
  2. String message = "Hello Java";
  3. // 取出第一个字
  4. char str = message.charAt(0);
  5. System.out.println(str);
  6. // 取出第二个字
  7. str = message.charAt(1);
  8. System.out.println(str);
  9. }

for循环得到每一个字符

  1. public static void main(String[] args) {
  2. print("今天天气挺好的");
  3. }
  4. public static void print(String message){
  5. for (int i = 0; i < message.length(); i++) {
  6. char str = message.charAt(i);
  7. System.out.println(str);
  8. }
  9. }

去掉字符串左右多余的空格

使用trim()方法

  1. String str = " 优课达 ";
  2. // 处理去空格
  3. String newStr = str.trim();
  4. }

字符串的常用方法(查找,拼接)

  1. String str = "Java是一种广泛使用的计算机编程语言,拥有跨平台、面向对象、泛型编程的特性,广泛应用于企业级Web应用开发和移动应用开发。任职于太阳微系统的詹姆斯·高斯林等人于1990年代初开发Java语言的雏形,最初被命名为Oak,目标设置在家用电器等小型系统的编程语言,应用在电视机、电话、闹钟、烤面包机等家用电器的控制和通信。由于这些智能化家电的市场需求没有预期的高,Sun公司放弃了该项计划。随着1990年代互联网的发展,Sun公司看见Oak在互联网上应用的前景,于是改造了Oak,于1995年5月以Java的名称正式发布。Java伴随着互联网的迅猛发展而发展,逐渐成为重要的网络编程语言。";
  2. //查找: indexOf();
  3. int index = str.indexOf("Java");
  4. //查找第二次出现java
  5. int index = str.indexOf("Java");
  6. index = str.indexOf("Java", index + 4);
  7. //拼接:substring();
  8. //打印出"java"之后的所有内容
  9. String newStr = str.substring(index+4);
  10. //打印出“java”之后的三个字节
  11. String newStr = str.substring(index+4,index+7);

判断字符串的“开始”或“结尾”

  1. String fileName = "报告.doc";
  2. //判断结尾是否为“.doc”
  3. if(fileName.endsWith(".doc")){
  4. System.out.println("是word文档");
  5. }
  6. }
  1. String url = "https://www.youkeda.com";
  2. //判断开头是否为“https”
  3. if(url.startsWith("https")){
  4. System.out.println("网址是安全的");
  5. }

字符串替换

replaceAll(“旧”,”新”);

  1. String str = "Java是一种广泛使用的计算机编程语言,拥有跨平台、面向对象、泛型编程的特性,广泛应用于企业级Web应用开发和移动应用开发。于1995年5月以Java的名称正式发布。Java伴随着互联网的迅猛发展而发展,逐渐成为重要的网络编程语言。";
  2. String newStr = str.replaceAll("Java","Python");
  3. //替换为空值(删除)
  4. String name = fileName.replaceAll(".doc","");

字符串分割

split()

  1. String text = "姓名|年龄|性别\n张三|20|男\n李四|18|男\n小花|18|女";
  2. // 使用 split 进行换行符的分隔,得到一个新的数组对象
  3. String[] data = text.split("\n");
  4. // 因为第一行是标题不是数据,所以我们需要把长度-1
  5. //(注意要使用小括号包围,因为要先计算长度再组合字符串)
  6. System.out.println("共有:" + (data.length - 1) + " 条记录");
  1. String text = "姓名|年龄|性别\n张三|20|男\n李四|18|男\n小花|18|女";
  2. // 使用 split 进行换行符的分割,得到一个新的数组对象
  3. String[] data = text.split("\n");
  4. // 因为第一行是标题不是数据,所以我们需要把长度-1
  5. // (注意要使用小括号包围,因为要先计算长度再组合字符串)
  6. System.out.println("共有:"+(data.length-1)+" 条记录");
  7. // 忽略第一行标题数据,所以我们把 i 设为1,从第二条记录开始
  8. for(int i=1;i<data.length;i++){
  9. // 使用 \\| 进行字符串分割,得到一个新数组对象
  10. String[] lines = data[i].split("\\|");
  11. System.out.println("姓名:"+lines[0]+" 年纪:"+lines[1]+" 性别:"+lines[2]);
  12. }

特殊字符的分割

  1. "."、"|"、"*"这三个字符作为分隔符时,需要加上“\\”作为转义符,eg:str.split("\\|");

大小写转换

转换为大写:toUpperCase();
转换为小写:toLowerCase();

  1. public static void main(String[] args) {
  2. String text = "ZhanSan";
  3. // 把拼音全部转化为大写字母
  4. String enName = text.toUpperCase();
  5. System.out.println(enName);
  6. }

字符串比较 equals()

.equals()

  1. String text = "字符串";
  2. // 使用 equals 方法判断是否相同
  3. if (text.equals("字符串")) {
  4. System.out.println("equals 方法字符串相等");
  5. }

数字和字符串转化

转化字符串为数字

  1. String text = "123";
  2. // 转化字符串为数字
  3. int a = Integer.parseInt(text);
  4. System.out.println(a);
  5. // 转化字符串为数字
  6. a = Integer.parseInt("100");
  7. System.out.println(a);

转化数字为字符串

  1. //与字符串拼接
  2. int a = 100;
  3. //使用空字符串相加数字,会自动变成字符串类型
  4. String str = ""+a;
  5. System.out.println(str);
  6. //String.valueOf()方法
  7. int a = 100;
  8. //使用valueOf强制把数字转化为字符串
  9. String str = String.valueOf(a);
  10. System.out.println(str);

java包管理

Java中导入包的语句是:

  1. import 包名+类名

位于类文件的最前面

自定义时间格式

一定要记得执行日期的格式化处理,再打印出该字符串

  1. import java.time.LocalDate;
  2. import java.time.format.DateTimeFormatter;
  3. public class DateTest5 {
  4. public static void main(String[] args) {
  5. //得到的默认日期格式yyyy-MM-dd
  6. LocalDate time = LocalDate.now();
  7. // 创建一个新的格式化方式
  8. DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
  9. // 执行日期的格式化处理,得到期望格式的日期字符串
  10. String timeStr = df.format(time);
  11. }
  12. }

获取当前时间具体的值

  1. import java.time.LocalDate;
  2. public class DateTest7 {
  3. public static void main(String[] args) {
  4. LocalDate time = LocalDate.now();
  5. // 得到当前时间所在年
  6. int year = time.getYear();
  7. System.out.println("当前年份 " + year);
  8. // 得到当前时间所在月
  9. int month = time.getMonth().getValue();
  10. System.out.println("当前月份 " + month);
  11. // 得到当前时间所在日
  12. int day = time.getDayOfMonth();
  13. System.out.println("当前日 " + day);
  14. // 得到当前时间所在星期数
  15. int dayOfWeek = time.getDayOfWeek().getValue();
  16. System.out.println("当前星期 " + dayOfWeek);
  17. }
  18. }

image.png

将字符串转化为日期

  1. import java.time.LocalDate;
  2. public class DateTest8 {
  3. public static void main(String[] args) {
  4. // 定义一个时间字符串
  5. String date = "2019-01-01";
  6. // 把字符串转化位 LocalDate 对象,并得到字符串匹配的日期
  7. LocalDate date2 = LocalDate.parse(date);
  8. // 打印出日期
  9. System.out.println(date2.toString());
  10. }
  11. }

如果日期的格式不是yyyy-MM-dd就需要增加一句下面的额代码,进行格式的转换。

  1. //()中的格式是当前传入字符串的格式
  2. DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy/MM/dd");

整体代码如下:

  1. import java.time.LocalDate;
  2. import java.time.format.DateTimeFormatter;
  3. public class DateTest81 {
  4. public static void main(String[] args) {
  5. String date = "2019/01/01";
  6. DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy/MM/dd");
  7. // 把字符串转化位 LocalDate 对象,并得到字符串匹配的日期
  8. LocalDate date2 = LocalDate.parse(date,df);
  9. // 打印出日期
  10. System.out.println(date2.toString());
  11. }
  12. }

计算日期

  1. import java.time.LocalDate;
  2. public class DateTest9 {
  3. public static void main(String[] args) {
  4. //5.1入住,住四天
  5. LocalDate leaveTime = getLeaveTime("2019-05-01", 4);
  6. System.out.println(leaveTime.toString());
  7. }
  8. public static LocalDate getLeaveTime(String checkInTime, int days) {
  9. // 把字符串转化为 LocalDate 类型
  10. LocalDate time = LocalDate.parse(checkInTime);
  11. // 使用 plusDays 添加天数,得到新的时间
  12. LocalDate leaveTime = time.plusDays(days);
  13. return leaveTime;
  14. }
  15. }

其他时间的计算

  1. import java.time.LocalDate;
  2. public class DateTest10 {
  3. public static void main(String[] args) {
  4. LocalDate now = LocalDate.now();
  5. System.out.println("当前:" + now.toString());
  6. System.out.println("加法运算");
  7. System.out.println("加1天:" + now.plusDays(1));
  8. System.out.println("加1周:" + now.plusWeeks(1));
  9. System.out.println("加1月:" + now.plusMonths(1));
  10. System.out.println("加1年:" + now.plusYears(1));
  11. System.out.println("减法运算");
  12. System.out.println("减1天:" + now.minusDays(1));
  13. System.out.println("减1周:" + now.minusWeeks(1));
  14. System.out.println("减1月:" + now.minusMonths(1));
  15. System.out.println("减1年:" + now.minusYears(1));
  16. }
  17. }

两个日期的比较

  1. import java.time.LocalDate;
  2. public class DateTest11 {
  3. public static void main(String[] args) {
  4. LocalDate now = LocalDate.now();
  5. // 可以对两个 LocalDateTime 进行比较,
  6. // 可以判断一个日期是否在另一个日期之前或之后,
  7. // 或者判断两个日期是否是同年同月同日。
  8. boolean isBefore = now.minusDays(1).isBefore(LocalDate.now());
  9. System.out.println("是否在当天之前:" + isBefore);
  10. boolean isAfter = now.plusDays(1).isAfter(LocalDate.now());
  11. System.out.println("是否在当天之后:" + isAfter);
  12. // 判断是否是当天
  13. boolean sameDate = now.isEqual(LocalDate.now());
  14. System.out.println("是否在当天:" + sameDate);
  15. }
  16. }

自定义类

com.youkeda.test.Hello.java 这样的Java类,我们的代码是这样的

  1. package com.youkeda.test;
  2. public class Hello {
  3. }

我们多了一个package包路径这样的语法,这个就是包的声明,注意这个语法,包路径是该Java所在的包目录。-个文件只有一个package语句,并且一般是在文件第一行

有了包和自定义类之后,我们就可以把代码放在不同的类中。

  1. package com.youkeda.test;
  2. import java.time.LocalDate;
  3. /**
  4. * 酒店工具类,用于计算入住和离店时间
  5. */
  6. public class HotelTool {
  7. /**
  8. * 根据离店时间和入住天数得到入住时间
  9. *
  10. * @param leaveTime
  11. * @param days
  12. * @return
  13. */
  14. public static LocalDate getCheckInTime(String leaveTime, int days) {
  15. // 把字符串转化为 LocalDate 类型
  16. LocalDate time = LocalDate.parse(leaveTime);
  17. // 使用 minusDays 减少天数,得到新的时间
  18. LocalDate checkInTime = time.minusDays(days);
  19. return checkInTime;
  20. }
  21. /**
  22. * 根据入住时间和入住天数得到离店时间
  23. *
  24. * @param checkInTime
  25. * @param days
  26. * @return
  27. */
  28. public static LocalDate getLeaveTime(String checkInTime, int days) {
  29. // 把字符串转化为 LocalDate 类型
  30. LocalDate time = LocalDate.parse(checkInTime);
  31. // 使用 plusDays 添加天数,得到新的时间
  32. LocalDate leaveTime = time.plusDays(days);
  33. return leaveTime;
  34. }
  35. }
  36. /*
  37. *我们可以通过导入包来任意调用你自定义的函数。
  38. */
  39. package com.youkeda.test;
  40. import java.time.LocalDate;
  41. /**
  42. * 酒店预定类
  43. */
  44. public class HotelOrder {
  45. public static void main(String[] args) {
  46. LocalDate checkIn = HotelTool.getCheckInTime("2019-01-03", 5);
  47. System.out.println(checkIn.toString());
  48. }
  49. }

注:在同一个包中的类可以省略下面这一句

  1. import com.youkeda.test.HotelTool;

实例化对象

  1. File myFile = new File("mywork.docx");

实例化对象之后,常用的方法

  1. //得到文件名
  2. String fileName = myFile.getName();
  3. //实例化 File,传入一个文件路径,文件路径使用 / 作为分隔符
  4. File myFile = new File("mywork/201408 人物角色.docx");
  5. String fileName = myFile.getName();
  6. //得到文件的完整路径(包含文件名)
  7. String getAbsolutePath()
  8. //得到文件路径(不包含文件名)
  9. String getPath()
  10. //判断文件是否存在
  11. boolean exists()
  12. File myFile = new File("mywork/201408 人物角色.docx");
  13. boolean fileExists = myFile.exists();
  14. //判断是否为文件
  15. boolean isFile()
  16. //实例化 File,传入一个文件路径
  17. File myFile = new File("mywork");
  18. boolean myFileIsFile = myFile.isFile();
  19. //判断是否为文件夹
  20. boolean isDirectory()
  21. //得到当前文件夹下的所有子文件,此时返回对象为File数组
  22. File[] listFiles()
  23. //实例化 File,传入一个文件路径
  24. File myFile = new File("mywork");
  25. // 使用 for 循环 语句遍历子文件
  26. for(File file : myFile.listFiles()){
  27. System.out.println(file.getName());
  28. }
  29. //得到当前文件的父文件实例(上一级文件夹)
  30. File getParentFile()
  31. //实例化 File,传入一个文件路径
  32. File myFile = new File("mywork/201408 人物角色.docx");
  33. File parentFile = myFile.getParentFile();
  34. //得到当前文件的大小,单位为byte
  35. long length()
  36. File myFile = new File("mywork/201408 人物角色.docx");
  37. long size = myFile.length();
  38. System.out.println(myFile.getName()+" 大小为:"+ size/1024 +"kb");

遍历文件夹并得到该文件夹的大小

  1. public static void main(String[] args) {
  2. File myfile = new File("mywork");
  3. long total = 0;
  4. for(File file: myfile.listFiles()){
  5. total = total+ file.length();
  6. }
  7. System.out.println(total/1024+"kb");
  8. }

构造函数

  1. /*
  2. 没有static 关键字
  3. 没有返回对象,连void都不需要写
  4. 方法名==类名称
  5. */
  6. public File(String pathname) {
  7. }

当我们执行实例化的时候,其实就是执行构造函数,同时搭配new关键字.

  1. new File(myfile,"201408 项目发布通知模板.xlsx");
  2. //执行下面的构造函数
  3. public File(File parent, String child) {
  4. //这个构造函数的第一个参数是父文件实例,
  5. //第二个参数子文件的名称,通过这个也可以得到一个文件,我们运行看看
  6. }

默认构造函数

  1. public class CustomFile{
  2. //类没有内容时会默认创建一个空参数的构造函数
  3. public CustomFile(){
  4. }
  5. }

类的实例化必须通过构造函数来才能完成的,所以如果用户没有自定义那么系统就给一个默认的。

默认构造函数的实例化

  1. CustomFile file = new CustomFile();

对象的属性和方法

对象的属性

对象的属性就是在一个类中创建的变量

  1. private String name;

例子

  1. public class CustomFile{
  2. private String name;
  3. private File parent;
  4. public CustomFile(String name){
  5. this.name = name;
  6. }
  7. public CustomFile(File parent,String name){
  8. this.parent = parent;
  9. this.name = name;
  10. }
  11. }

这个时候的this其实指的就是CustomFile类被实例化后的对象,this . name就是指private String name;这个变量,
this.name = name; 就是说给属性name赋值,值是参数name,

我们把代码的参数名称换一下,大家可能更容易理解

  1. public class CustomFile{
  2. private String name;
  3. private File parent;
  4. public CustomFile(String _name){
  5. this.name = _name;
  6. }
  7. public CustomFile(File _parent,String _name){
  8. this.parent = _parent;
  9. this.name = _name;
  10. }
  11. //新增类方法
  12. public String getSize(){
  13. File file = new File(this.name);
  14. long size = file.length();
  15. return size/1024+"kb";
  16. }
  17. }

这其实就是对象属性值操作的规范,记住它即可!

对象方法

没有static关键字
除此之外,静态方法是不能获取对象属性的,只有对象方法才能获取对象属性

ArrayList

ArrayList本质是动态数组对象,可以方便的存储集合对象,我们一般会将同一类型的数据存储在ArrayList中

  1. import java.util.ArrayList;
  2. // 这里的 Java 对象类型可以是任意的对象类型
  3. // 比如 String、Integer、CustomFile 等
  4. // 这里的 <> 是 Java 泛型的规范,以后我们还会介绍
  5. ArrayList<Java 对象类型> list = new ArrayList<>();

add()方法

例子

  1. import java.util.ArrayList;
  2. public class ArrayListTest1{
  3. public static void main(String[] args){
  4. // 创建一个 ArrayList 存储字符串集合
  5. ArrayList<String> strs = new ArrayList<>();
  6. // 添加数据到 ArrayList 实例里
  7. strs.add("张三");
  8. strs.add("李四");
  9. }
  10. }

get/size方法

  1. import java.util.ArrayList;
  2. public class ArrayListTest1 {
  3. public static void main(String[] args) {
  4. // 创建一个 ArrayList 存储字符串集合
  5. ArrayList<String> strs = new ArrayList<>();
  6. // 添加数据到 ArrayList 实例里
  7. strs.add("张三");
  8. strs.add("李四");
  9. // 获取集合的长度
  10. int size = strs.size();
  11. // 使用 for 循环迭代每一条记录
  12. for(int i=0;i<size;i++){
  13. // 根据索引获取值,值的类型是 String
  14. String str = strs.get(i);
  15. System.out.println(str);
  16. }
  17. }
  18. }