05-java常用api类

1._String类

  1. String 类在 java.lang 包下,所以使用的时候不需要导包
  2. String 类代表字符串,Java 程序中的所有字符串文字(例如“abc”)都被实现为此类的实例也就是说,Java 程序中所有的双引号字符串,都是 String 类的对象
  3. 字符串不可变,它们的值在创建后不能被更改

1.1._String类的构造方法

常用的构造方法

package com.itheima.string;

public class Demo2StringConstructor {
    
    
    /*
        String类常见构造方法:

            public String() : 创建一个空白字符串对象,不含有任何内容
            public String(char[] chs) : 根据字符数组的内容,来创建字符串对象
            public String(String original) : 根据传入的字符串内容,来创建字符串对象
            String s = “abc”;  直接赋值的方式创建字符串对象,内容就是abc

         注意:
                String这个类比较特殊, 打印其对象名的时候, 不会出现内存地址
                而是该对象所记录的真实内容.

                面向对象-继承, Object类
     */
    public static void main(String[] args) {
    
    
        // public String() : 创建一个空白字符串对象,不含有任何内容
        String s1 = new String();
        System.out.println(s1);

        // public String(char[] chs) : 根据字符数组的内容,来创建字符串对象
        char[] chs = {
    
    'a','b','c'};
        String s2 = new String(chs);
        System.out.println(s2);

        // public String(String original) : 根据传入的字符串内容,来创建字符串对象
        String s3 = new String("123");
        System.out.println(s3);
    }
}

1.2._创建字符串对象的区别对比

  • 通过构造方法创建

    通过 new 创建的字符串对象,每一次 new 都会申请一个内存空间,虽然内容相同,但是地址值不同

  • 直接赋值方式创建

    “”方式给出的字符串,只要字符序列相同(顺序和大小写),无论在程序代码中出现几次,JVM 都只会建立一个 String 对象,并在字符串池中维护

1.3._常用案例

用户登录案例

案例需求 :

已知用户名和密码,请用程序实现模拟用户登录。总共给三次机会,登录之后,给出相应的提示

实现步骤 :

  1. 已知用户名和密码,定义两个字符串表示即可
  2. 键盘录入要登录的用户名和密码,用 Scanner 实现
  3. 拿键盘录入的用户名、密码和已知的用户名、密码进行比较,给出相应的提示。
  4. 字符串的内容比较,用equals() 方法实现
  5. 用循环实现多次机会,这里的次数明确,采用for循环实现,并在登录成功的时候,使用break结束循

代码实现 :

package com.itheima.test;

import java.util.Scanner;

public class Test1 {
    
    
    /*
        需求:已知用户名和密码,请用程序实现模拟用户登录。
              总共给三次机会,登录之后,给出相应的提示

        思路:
        1. 已知用户名和密码,定义两个字符串表示即可
        2. 键盘录入要登录的用户名和密码,用 Scanner 实现
        3. 拿键盘录入的用户名、密码和已知的用户名、密码进行比较,给出相应的提示。
            字符串的内容比较,用equals() 方法实现
        4. 用循环实现多次机会,这里的次数明确,采用for循环实现,并在登录成功的时候,使用break结束循环

     */
    public static void main(String[] args) {
    
    
        // 1. 已知用户名和密码,定义两个字符串表示即可
        String username = "admin";
        String password = "123456";
        // 2. 键盘录入要登录的用户名和密码,用 Scanner 实现
        Scanner sc = new Scanner(System.in);
        // 4. 用循环实现多次机会,这里的次数明确,采用for循环实现
        for(int i = 1; i <= 3; i++){
    
    
            System.out.println("请输入用户名:");
            String scUsername = sc.nextLine();
            System.out.println("请输入密码:");
            String scPassword = sc.nextLine();
            // 3. 拿键盘录入的用户名、密码和已知的用户名、密码进行比较,给出相应的提示。
            if(username.equals(scUsername) && password.equals(scPassword)){
    
    
                System.out.println("登录成功");
                break;
            }else{
    
    
                if(i == 3){
    
    
                    System.out.println("您的登录次数已达到今日上限, 请明天再来");
                }else{
    
    
                    System.out.println("登录失败,您还剩余" + (3-i) +"次机会");
                }

            }
        }

    }
}

手机号屏蔽-字符串截取

案例需求 :

以字符串的形式从键盘接受一个手机号,将中间四位号码屏蔽
最终效果为:1561234

实现步骤 :

  1. 键盘录入一个字符串,用 Scanner 实现
  2. 截取字符串前三位
  3. 截取字符串后四位
  4. 将截取后的两个字符串,中间加上进行拼接,输出结果

代码实现 :

package com.itheima.test;

import java.util.Scanner;

public class Test5 {
    
    
    /*
        需求:以字符串的形式从键盘接受一个手机号,将中间四位号码屏蔽
        最终效果为:156****1234

        思路:
        1. 键盘录入一个字符串,用 Scanner 实现
        2. 截取字符串前三位
        3. 截取字符串后四位
        4. 将截取后的两个字符串,中间加上****进行拼接,输出结果

     */
    public static void main(String[] args) {
    
    
        // 1. 键盘录入一个字符串,用 Scanner 实现
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入手机号:");
        String telString = sc.nextLine();
        // 2. 截取字符串前三位
        String start = telString.substring(0,3);
        // 3. 截取字符串后四位
        String end = telString.substring(7);
        // 4. 将截取后的两个字符串,中间加上****进行拼接,输出结果
        System.out.println(start + "****" + end);
    }
}

敏感词替换-字符串替换

案例需求 :

键盘录入一个 字符串,如果字符串中包含(TMD),则使用***替换

实现步骤 :

  1. 键盘录入一个字符串,用 Scanner 实现
  2. 替换敏感词
    String replace(CharSequence target, CharSequence replacement)
    将当前字符串中的target内容,使用replacement进行替换,返回新的字符串
  3. 输出结果

代码实现 :

package com.itheima.test;

import java.util.Scanner;

public class Test6 {
    
    
    /*
        需求:键盘录入一个 字符串,如果字符串中包含(TMD),则使用***替换

        思路:
        1. 键盘录入一个字符串,用 Scanner 实现
        2. 替换敏感词
                String replace(CharSequence target, CharSequence replacement)
                将当前字符串中的target内容,使用replacement进行替换,返回新的字符串
        3. 输出结果

     */
    public static void main(String[] args) {
    
    
        // 1. 键盘录入一个字符串,用 Scanner 实现
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入:");
        String s = sc.nextLine();
        // 2. 替换敏感词
        String result = s.replace("TMD","***");
        // 3. 输出结果
        System.out.println(result);
    }
}

切割字符串

案例需求 :

以字符串的形式从键盘录入学生信息,例如:“张三 , 23”

从该字符串中切割出有效数据,封装为Student学生对象

实现步骤 :

  1. 编写Student类,用于封装数据
  2. 键盘录入一个字符串,用 Scanner 实现
  3. 根据逗号切割字符串,得到(张三)(23)
    String[] split(String regex) :根据传入的字符串作为规则进行切割
    将切割后的内容存入字符串数组中,并将字符串数组返回
  4. 从得到的字符串数组中取出元素内容,通过Student类的有参构造方法封装为对象
  5. 调用对象getXxx方法,取出数据并打印。

代码实现 :

package com.itheima.test;

import com.itheima.domain.Student;

import java.util.Scanner;

public class Test7 {
    
    
    /*
         需求:以字符串的形式从键盘录入学生信息,例如:“张三 , 23”
                从该字符串中切割出有效数据,封装为Student学生对象
         思路:
            1. 编写Student类,用于封装数据
            2. 键盘录入一个字符串,用 Scanner 实现
            3. 根据逗号切割字符串,得到(张三)(23)
                    String[] split(String regex) :根据传入的字符串作为规则进行切割
                    将切割后的内容存入字符串数组中,并将字符串数组返回
            4. 从得到的字符串数组中取出元素内容,通过Student类的有参构造方法封装为对象
            5. 调用对象getXxx方法,取出数据并打印。

     */
    public static void main(String[] args) {
    
    
        // 2. 键盘录入一个字符串,用 Scanner 实现
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入学生信息:");
        String stuInfo = sc.nextLine();
        // stuInfo = "张三,23";
        // 3. 根据逗号切割字符串,得到(张三)(23)
        String[] sArr = stuInfo.split(",");

//        System.out.println(sArr[0]);
//        System.out.println(sArr[1]);

        // 4. 从得到的字符串数组中取出元素内容,通过Student类的有参构造方法封装为对象
        Student stu = new Student(sArr[0],sArr[1]);

        // 5. 调用对象getXxx方法,取出数据并打印。
        System.out.println(stu.getName() + "..." + stu.getAge());
    }
}

1.4._String类的常用方法

    public boolean equals(Object anObject)  比较字符串的内容,严格区分大小写

  public boolean equalsIgnoreCase(String anotherString)  比较字符串的内容,忽略大小写

  public int length()  返回此字符串的长度

  public char charAt(int index)  返回指定索引处的 charpublic char[] toCharArray()  将字符串拆分为字符数组后返回

  public String substring(int beginIndex, int endIndex)  根据开始和结束索引进行截取,得到新的字符串(包含头,不包含尾)

  public String substring(int beginIndex)  从传入的索引处截取,截取到末尾,得到新的字符串

  public String replace(CharSequence target, CharSequence replacement)  使用新值,将字符串中的旧值替换,得到新的字符串

  public String[] split(String regex)  根据传入的规则切割字符串,得到字符串数组

2._StringBuilder类

2.1._StringBuilder类概述

StringBuilder 是一个可变的字符串类,我们可以把它看成是一个容器,这里的可变指的是 StringBuilder 对象中的内容是可变的

2.2._StringBuilder类和String类的区别

  • **String类:**内容是不可变的
  • **StringBuilder类:**内容是可变的

2.3._StringBuilder类的构造方法

常用的构造方法

方法名 说明
public StringBuilder() 创建一个空白可变字符串对象,不含有任何内容
public StringBuilder(String str) 根据字符串的内容,来创建可变字符串对象

示例代码

public class StringBuilderDemo01 {
    
    
    public static void main(String[] args) {
    
    
        //public StringBuilder():创建一个空白可变字符串对象,不含有任何内容
        StringBuilder sb = new StringBuilder();
        System.out.println("sb:" + sb);
        System.out.println("sb.length():" + sb.length());

        //public StringBuilder(String str):根据字符串的内容,来创建可变字符串对象
        StringBuilder sb2 = new StringBuilder("hello");
        System.out.println("sb2:" + sb2);
        System.out.println("sb2.length():" + sb2.length());
    }
}

2.4._StringBuilder常用的成员方法

  • 添加和反转方法

    方法名 说明
    public StringBuilder append(任意类型) 添加数据,并返回对象本身
    public StringBuilder reverse() 返回相反的字符序列
  • 示例代码

public class StringBuilderDemo01 {
    
    
    public static void main(String[] args) {
    
    
        //创建对象
        StringBuilder sb = new StringBuilder();

        //public StringBuilder append(任意类型):添加数据,并返回对象本身
//        StringBuilder sb2 = sb.append("hello");
//
//        System.out.println("sb:" + sb);
//        System.out.println("sb2:" + sb2);
//        System.out.println(sb == sb2);

//        sb.append("hello");
//        sb.append("world");
//        sb.append("java");
//        sb.append(100);

        //链式编程
        sb.append("hello").append("world").append("java").append(100);

        System.out.println("sb:" + sb);

        //public StringBuilder reverse():返回相反的字符序列
        sb.reverse();
        System.out.println("sb:" + sb);
    }
}

2.5._StringBuilder和String相互转换

  • StringBuilder转换为String

    public String toString():通过 toString() 就可以实现把 StringBuilder 转换为 String

  • String转换为StringBuilder

    public StringBuilder(String s):通过构造方法就可以实现把 String 转换为 StringBuilder

  • 示例代码

public class StringBuilderDemo02 {
    
    
    public static void main(String[] args) {
    
    
        /*
        //StringBuilder 转换为 String
        StringBuilder sb = new StringBuilder();
        sb.append("hello");

        //String s = sb; //这个是错误的做法

        //public String toString():通过 toString() 就可以实现把 StringBuilder 转换为 String
        String s = sb.toString();
        System.out.println(s);
        */

        //String 转换为 StringBuilder
        String s = "hello";

        //StringBuilder sb = s; //这个是错误的做法

        //public StringBuilder(String s):通过构造方法就可以实现把 String 转换为 StringBuilder
        StringBuilder sb = new StringBuilder(s);

        System.out.println(sb);
    }
}

2.6._StringBuilder拼接字符串案例

案例需求 :

定义一个方法,把 int 数组中的数据按照指定的格式拼接成一个字符串返回,调用该方法,

并在控制台输出结果。例如,数组为int[] arr = {1,2,3}; ,执行方法后的输出结果为:[1, 2, 3]

实现步骤 :

  1. 定义一个 int 类型的数组,用静态初始化完成数组元素的初始化
  2. 定义一个方法,用于把 int 数组中的数据按照指定格式拼接成一个字符串返回。
    返回值类型 String,参数列表 int[] arr
  3. 在方法中用 StringBuilder 按照要求进行拼接,并把结果转成 String 返回
  4. 调用方法,用一个变量接收结果
  5. 输出结果

代码实现 :

/*
    思路:
        1:定义一个 int 类型的数组,用静态初始化完成数组元素的初始化
        2:定义一个方法,用于把 int 数组中的数据按照指定格式拼接成一个字符串返回。
          返回值类型 String,参数列表 int[] arr
        3:在方法中用 StringBuilder 按照要求进行拼接,并把结果转成 String 返回
        4:调用方法,用一个变量接收结果
        5:输出结果
 */
public class StringBuilderTest01 {
    
    
    public static void main(String[] args) {
    
    
        //定义一个 int 类型的数组,用静态初始化完成数组元素的初始化
        int[] arr = {
    
    1, 2, 3};

        //调用方法,用一个变量接收结果
        String s = arrayToString(arr);

        //输出结果
        System.out.println("s:" + s);

    }

    //定义一个方法,用于把 int 数组中的数据按照指定格式拼接成一个字符串返回
    /*
        两个明确:
            返回值类型:String
            参数:int[] arr
     */
    public static String arrayToString(int[] arr) {
    
    
        //在方法中用 StringBuilder 按照要求进行拼接,并把结果转成 String 返回
        StringBuilder sb = new StringBuilder();

        sb.append("[");

        for(int i=0; i<arr.length; i++) {
    
    
            if(i == arr.length-1) {
    
    
                sb.append(arr[i]);
            } else {
    
    
                sb.append(arr[i]).append(", ");
            }
        }

        sb.append("]");

        String s = sb.toString();

        return  s;
    }
}

3._Math

Math类概述

Math 包含执行基本数字运算的方法

Math中方法的调用方式

Math类中无构造方法,但内部的方法都是静态的,则可以通过 类名.进行调用

Math类的常用方法

方法名 方法名 说明
public static int abs(int a) 返回参数的绝对值
public static double ceil(double a) 返回大于或等于参数的最小double值,等于一个整数
public static double floor(double a) 返回小于或等于参数的最大double值,等于一个整数
public static int round(float a) 按照四舍五入返回最接近参数的int
public static int max(int a,int b) 返回两个int值中的较大值
public static int min(int a,int b) 返回两个int值中的较小值
public static double pow (double a,double b) 返回a的b次幂的值
public static double random() 返回值为double的正值,[0.0,1.0)

4._System

  • System类的常用方法

    方法名 说明
    public static void exit(int status) 终止当前运行的 Java 虚拟机,非零表示异常终止
    public static long currentTimeMillis() 返回当前时间(以毫秒为单位)
  • 示例代码

    • 需求:在控制台输出1-10000,计算这段代码执行了多少毫秒
    public class SystemDemo {
          
          
        public static void main(String[] args) {
          
          
            // 获取开始的时间节点
            long start = System.currentTimeMillis();
            for (int i = 1; i <= 10000; i++) {
          
          
                System.out.println(i);
            }
            // 获取代码运行结束后的时间节点
            long end = System.currentTimeMillis();
            System.out.println("共耗时:" + (end - start) + "毫秒");
        }
        
    }
    

5._Object类的toString方法

  • Object类概述

    • Object 是类层次结构的根,每个类都可以将 Object 作为超类。所有类都直接或者间接的继承自该类,换句话说,该类所具备的方法,所有类都会有一份

    • 直接打印一个对象就是打印这个对象的toString的返回值

    • Object的toString得到的是对象的地址值

    • 一般会对toString重写,即打印类的数据而不是地址值

    • @Override
      public String toString() {
              
              
          return "Student{" +
                  "name='" + name + '\'' +
                  ", age=" + age +
                  '}';
      }
      
  • toString方法的作用:

    • 以良好的格式,更方便的展示对象中的属性值

6._Object类的equals方法

  • equals方法的作用

    • 用于对象之间的比较,返回true和false的结果
    • 举例:s1.equals(s2); s1和s2是两个对象
  • 重写equals方法的场景

    • 不希望比较对象的地址值,想要结合对象属性进行比较的时候。
  • 重写equals方法的方式

      1. alt + insert 选择equals() and hashCode(),IntelliJ Default,一路next,finish即可
      1. 在类的空白区域,右键 -> Generate -> 选择equals() and hashCode(),后面的同上。
  • 示例代码:

    class Student {
          
          
        private String name;
        private int age;
    
        public Student() {
          
          
        }
    
        public Student(String name, int age) {
          
          
            this.name = name;
            this.age = age;
        }
    
        public String getName() {
          
          
            return name;
        }
    
        public void setName(String name) {
          
          
            this.name = name;
        }
    
        public int getAge() {
          
          
            return age;
        }
    
        public void setAge(int age) {
          
          
            this.age = age;
        }
    
        @Override
        public boolean equals(Object o) {
          
          
            //this -- s1
            //o -- s2
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
    
            Student student = (Student) o; //student -- s2
    
            if (age != student.age) return false;
            return name != null ? name.equals(student.name) : student.name == null;
        }
    }
    public class ObjectDemo {
          
          
        public static void main(String[] args) {
          
          
            Student s1 = new Student();
            s1.setName("林青霞");
            s1.setAge(30);
    
            Student s2 = new Student();
            s2.setName("林青霞");
            s2.setAge(30);
    
            //需求:比较两个对象的内容是否相同
            System.out.println(s1.equals(s2));
        }
    }
    
    
  • 面试题

    // 看程序,分析结果
    String s = “abc”;
    StringBuilder sb = new StringBuilder(“abc”);
    s.equals(sb); 
    sb.equals(s); 
    
    public class InterviewTest {
          
          
        public static void main(String[] args) {
          
          
            String s1 = "abc";
            StringBuilder sb = new StringBuilder("abc");
            //1.此时调用的是String类中的equals方法.
            //保证参数也是字符串,否则不会比较属性值而直接返回false
            //System.out.println(s1.equals(sb)); // false
    
            //StringBuilder类中是没有重写equals方法,用的就是Object类中的.
            System.out.println(sb.equals(s1)); // false
        }
    }
    

7._Objects

  • 常用方法

    方法名 说明
    public static String toString(对象) 返回参数中对象的字符串表示形式。
    public static String toString(对象, 默认字符串) 返回对象的字符串表示形式。
    public static Boolean isNull(对象) 判断对象是否为空
    public static Boolean nonNull(对象) 判断对象是否不为空
  • 示例代码

    学生类

    class Student {
          
          
          private String name;
          private int age;
    
          public Student() {
          
          
          }
    
          public Student(String name, int age) {
          
          
              this.name = name;
              this.age = age;
          }
    
          public String getName() {
          
          
              return name;
          }
    
          public void setName(String name) {
          
          
              this.name = name;
          }
    
          public int getAge() {
          
          
              return age;
          }
    
          public void setAge(int age) {
          
          
              this.age = age;
          }
    
          @Override
          public String toString() {
          
          
              return "Student{" +
                      "name='" + name + '\'' +
                      ", age=" + age +
                      '}';
          }
      }
    

    测试类

    public class MyObjectsDemo {
          
          
              public static void main(String[] args) {
          
          
          //        public static String toString(对象): 返回参数中对象的字符串表示形式。
          //        Student s = new Student("小罗同学",50);
          //        String result = Objects.toString(s);
          //        System.out.println(result);
          //        System.out.println(s);
    
          //        public static String toString(对象, 默认字符串): 返回对象的字符串表示形式。如果对象为空,那么返回第二个参数.
                  //Student s = new Student("小花同学",23);
          //        Student s = null;
          //        String result = Objects.toString(s, "随便写一个");
          //        System.out.println(result);
          
          //        public static Boolean isNull(对象): 判断对象是否为空
                  //Student s = null;
          //        Student s = new Student();
          //        boolean result = Objects.isNull(s);
          //        System.out.println(result);
    
          //        public static Boolean nonNull(对象): 判断对象是否不为空
                  //Student s = new Student();
                  Student s = null;
                  boolean result = Objects.nonNull(s);
                  System.out.println(result);
              }
      }
    

8._BigDecimal

  • 作用

    可以用来进行精确计算

  • 构造方法

    方法名 说明
    BigDecimal(double val) 参数为double
    BigDecimal(String val) 参数为String
  • 常用方法

    方法名 说明
    public BigDecimal add(另一个BigDecimal对象) 加法
    public BigDecimal subtract (另一个BigDecimal对象) 减法
    public BigDecimal multiply (另一个BigDecimal对象) 乘法
    public BigDecimal divide (另一个BigDecimal对象) 除法
    public BigDecimal divide (另一个BigDecimal对象,精确几位,舍入模式) 除法
  • 总结

    1. BigDecimal是用来进行精确计算的
    2. 创建BigDecimal的对象,构造方法使用参数类型为字符串的。
    3. 四则运算中的除法,如果除不尽请使用divide的三个参数的方法。

    代码示例:

    BigDecimal divide = bd1.divide(参与运算的对象,小数点后精确到多少位,舍入模式);
    参数1 ,表示参与运算的BigDecimal 对象。
    参数2 ,表示小数点后面精确到多少位
    参数3 ,舍入模式  
      BigDecimal.ROUND_UP  进一法
      BigDecimal.ROUND_FLOOR 去尾法
      BigDecimal.ROUND_HALF_UP 四舍五入
    
    

9._包装类

9.1._基本类型包装类

  • 基本类型包装类的作用

    将基本数据类型封装成对象的好处在于可以在对象中定义更多的功能方法操作该数据

    常用的操作之一:用于基本数据类型与字符串之间的转换

  • 基本类型对应的包装类

    基本数据类型 包装类
    byte Byte
    short Short
    int Integer
    long Long
    float Float
    double Double
    char Character
    boolean Boolean

9.2._Integer类

  • Integer类概述

    包装一个对象中的原始类型 int 的值

  • Integer类构造方法

    方法名 说明
    public Integer(int value) 根据 int 值创建 Integer 对象(过时)
    public Integer(String s) 根据 String 值创建 Integer 对象(过时)
  • 示例代码

    public class IntegerDemo {
          
          
        public static void main(String[] args) {
          
          
            //public Integer(int value):根据 int 值创建 Integer 对象(过时)
            Integer i1 = new Integer(100);
            System.out.println(i1);
    
            //public Integer(String s):根据 String 值创建 Integer 对象(过时)
            Integer i2 = new Integer("100");
    //        Integer i2 = new Integer("abc"); //NumberFormatException
            System.out.println(i2);
            System.out.println("--------");
    
            //public static Integer valueOf(int i):返回表示指定的 int 值的 Integer 实例
            Integer i3 = Integer.valueOf(100);
            System.out.println(i3);
    
            //public static Integer valueOf(String s):返回一个保存指定值的Integer对象 String
            Integer i4 = Integer.valueOf("100");
            System.out.println(i4);
        }
    }
    
    

9.3._自动拆箱和自动装箱

  • 自动装箱

    把基本数据类型转换为对应的包装类类型

  • 自动拆箱

    把包装类类型转换为对应的基本数据类型

  • 示例代码

    Integer i = 100;  // 自动装箱
    i += 200;         // i = i + 200;  i + 200 自动拆箱;i = i + 200; 是自动装箱
    
    

9.4._int和String类型的相互转换(记忆)

  • int转换为String

    • 转换方式

      • 方式一:直接在数字后加一个空字符串
      • 方式二:通过String类静态方法valueOf()
    • 示例代码

      public class IntegerDemo {
              
              
          public static void main(String[] args) {
              
              
              //int --- String
              int number = 100;
              //方式1
              String s1 = number + "";
              System.out.println(s1);
              //方式2
              //public static String valueOf(int i)
              String s2 = String.valueOf(number);
              System.out.println(s2);
              System.out.println("--------");
          }
      }
      
      
  • String转换为int

    • 转换方式

      • 方式一:先将字符串数字转成Integer,再调用valueOf()方法
      • 方式二:通过Integer静态方法parseInt()进行转换
    • 示例代码

      public class IntegerDemo {
              
              
          public static void main(String[] args) {
              
              
              //String --- int
              String s = "100";
              //方式1:String --- Integer --- int
              Integer i = Integer.valueOf(s);
              //public int intValue()
              int x = i.intValue();
              System.out.println(x);
              //方式2
              //public static int parseInt(String s)
              int y = Integer.parseInt(s);
              System.out.println(y);
          }
      }
      
      

9.5._字符串数据排序案例(应用)

  • 案例需求

    有一个字符串:“91 27 46 38 50”,请写程序实现最终输出结果是:27 38 46 50 91

  • 代码实现

    public class IntegerTest {
          
          
        public static void main(String[] args) {
          
          
            //定义一个字符串
            String s = "91 27 46 38 50";
    
            //把字符串中的数字数据存储到一个int类型的数组中
            String[] strArray = s.split(" ");
    //        for(int i=0; i<strArray.length; i++) {
          
          
    //            System.out.println(strArray[i]);
    //        }
    
            //定义一个int数组,把 String[] 数组中的每一个元素存储到 int 数组中
            int[] arr = new int[strArray.length];
            for(int i=0; i<arr.length; i++) {
          
          
                arr[i] = Integer.parseInt(strArray[i]);
            }
    
            //对 int 数组进行排序
            Arrays.sort(arr);
    
            for(int i=0; i<arr.length; i++){
          
          
             System.out.print(arr[i] + " ");
            }
    }
    
    

10._Arrays

  • Arrays的常用方法

    方法名 说明
    public static String toString(int[] a) 返回指定数组的内容的字符串表示形式
    public static void sort(int[] a) 按照数字顺序排列指定的数组
    public static int binarySearch(int[] a, int key) 利用二分查找返回指定元素的索引
  • 示例代码

    public class MyArraysDemo {
          
          
          public static void main(String[] args) {
          
          
      //        public static String toString(int[] a)    返回指定数组的内容的字符串表示形式
      //        int [] arr = {3,2,4,6,7};
      //        System.out.println(Arrays.toString(arr));
    
      //        public static void sort(int[] a)    按照数字顺序排列指定的数组
      //        int [] arr = {3,2,4,6,7};
      //        Arrays.sort(arr);
      //        System.out.println(Arrays.toString(arr));
    
      //        public static int binarySearch(int[] a, int key) 利用二分查找返回指定元素的索引
              int [] arr = {
          
          1,2,3,4,5,6,7,8,9,10};
              int index = Arrays.binarySearch(arr, 0);
              System.out.println(index);
              //1,数组必须有序
              //2.如果要查找的元素存在,那么返回的是这个元素实际的索引
              //3.如果要查找的元素不存在,那么返回的是 (-插入点-1)
                  //插入点:如果这个元素在数组中,他应该在哪个索引上.
          }
      }
    
    

11._时间日期类

11.1._Date类(应用)

  • 计算机中时间原点

    1970年1月1日 00 : 00 : 00

  • 时间换算单位

    1秒 = 1000毫秒

  • Date类概述

    Date 代表了一个特定的时间,精确到毫秒

  • Date类构造方法

    方法名 说明
    public Date() 分配一个 Date对象,并初始化,以便它代表它被分配的时间,精确到毫秒
    public Date(long date) 分配一个 Date对象,并将其初始化为表示从标准基准时间起指定的毫秒数
  • 示例代码

    public class DateDemo01 {
          
          
        public static void main(String[] args) {
          
          
            //public Date():分配一个 Date对象,并初始化,以便它代表它被分配的时间,精确到毫秒
            Date d1 = new Date();
            System.out.println(d1);
    
            //public Date(long date):分配一个 Date对象,并将其初始化为表示从标准基准时间起指定的毫秒数
            long date = 1000*60*60;
            Date d2 = new Date(date);
            System.out.println(d2);
        }
    }
    

11.2._Date类常用方法(应用)

  • 常用方法

    方法名 说明
    public long getTime() 获取的是日期对象从1970年1月1日 00 : 00 : 00到现在的毫秒值
    public void setTime(long time) 设置时间,给的是毫秒值
  • 示例代码

    public class DateDemo02 {
          
          
        public static void main(String[] args) {
          
          
            //创建日期对象
            Date d = new Date();
    
            //public long getTime():获取的是日期对象从1970年1月1日 00 : 00 : 00到现在的毫秒值
    //        System.out.println(d.getTime());
    //        System.out.println(d.getTime() * 1.0 / 1000 / 60 / 60 / 24 / 365 + "年");
    
            //public void setTime(long time):设置时间,给的是毫秒值
    //        long time = 1000*60*60;
            long time = System.currentTimeMillis();
            d.setTime(time);
    
            System.out.println(d);
        }
    }
    

11.3._SimpleDateFormat类(常用)

  • SimpleDateFormat类概述

    SimpleDateFormat是一个具体的类,用于以区域设置敏感的方式格式化和解析日期。

  • SimpleDateFormat类构造方法

    方法名 说明
    public SimpleDateFormat() 构造一个SimpleDateFormat,使用默认模式和日期格式
    public SimpleDateFormat(String pattern) 构造一个SimpleDateFormat使用给定的模式和默认的日期格式
  • SimpleDateFormat类的常用方法

    • 格式化(从Date到String)
      • public final String format(Date date):将日期格式化成日期/时间字符串
    • 解析(从String到Date)
      • public Date parse(String source):从给定字符串的开始解析文本以生成日期
  • 示例代码

    public class SimpleDateFormatDemo {
          
          
        public static void main(String[] args) throws ParseException {
          
          
            //格式化:从 Date 到 String
            Date d = new Date();
    //        SimpleDateFormat sdf = new SimpleDateFormat();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            String s = sdf.format(d);
            System.out.println(s);
            System.out.println("--------");
    
            //从 String 到 Date
            String ss = "2048-08-09 11:11:11";
            //ParseException
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date dd = sdf2.parse(ss);
            System.out.println(dd);
        }
    }
    

11.4._时间日期类练习 (应用)

  • 需求

    秒杀开始时间是2020年11月11日 00 : 00 : 00,结束时间是2020年11月11日 00 : 10 : 00,用户小贾下单时间是2020年11月11日 00 : 03 : 47,用户小皮下单时间是2020年11月11日 00 : 10 : 11,判断用户有没有成功参与秒杀活动

  • 实现步骤

    1. 判断下单时间是否在开始到结束的范围内
    2. 把字符串形式的时间变成毫秒值
  • 代码实现

    public class DateDemo5 {
          
          
        public static void main(String[] args) throws ParseException {
          
          
            //开始时间:2020年11月11日 0:0:0
            //结束时间:2020年11月11日 0:10:0
    
            //小贾2020年11月11日 0:03:47
            //小皮2020年11月11日 0:10:11
    
            //1.判断两位同学的下单时间是否在范围之内就可以了。
    
            //2.要把每一个时间都换算成毫秒值。
    
            String start = "2020年11月11日 0:0:0";
            String end = "2020年11月11日 0:10:0";
    
            String jia = "2020年11月11日 0:03:47";
            String pi = "2020年11月11日 0:10:11";
    
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            long startTime = sdf.parse(start).getTime();
            long endTime = sdf.parse(end).getTime();
    
    //        System.out.println(startTime);
    //        System.out.println(endTime);
            long jiaTime = sdf.parse(jia).getTime();
            long piTime = sdf.parse(pi).getTime();
    
            if(jiaTime >= startTime && jiaTime <= endTime){
          
          
                System.out.println("小贾同学参加上了秒杀活动");
            }else{
          
          
                System.out.println("小贾同学没有参加上秒杀活动");
            }
    
            System.out.println("------------------------");
    
            if(piTime >= startTime && piTime <= endTime){
          
          
                System.out.println("小皮同学参加上了秒杀活动");
            }else{
          
          
                System.out.println("小皮同学没有参加上秒杀活动");
            }
    
        }
      
    }
    

12._JDK8时间日期类

12.1._JDK8新增日期类 (理解)

  • LocalDate 表示日期(年月日)
  • LocalTime 表示时间(时分秒)
  • LocalDateTime 表示时间+ 日期 (年月日时分秒)

12.2 LocalDateTime创建方法 (应用)

  • 方法说明

    方法名 说明
    public static LocalDateTime now() 获取当前系统时间
    public static LocalDateTime of (年, 月 , 日, 时, 分, 秒) 使用指定年月日和时分秒初始化一个LocalDateTime对象
  • 示例代码

    public class JDK8DateDemo2 {
          
          
        public static void main(String[] args) {
          
          
            LocalDateTime now = LocalDateTime.now();
            System.out.println(now);
    
            LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 11, 11, 11, 11);
            System.out.println(localDateTime);
        }
    }
    

12.3 LocalDateTime获取方法 (应用)

  • 方法说明

    方法名 说明
    public int getYear() 获取年
    public int getMonthValue() 获取月份(1-12)
    public int getDayOfMonth() 获取月份中的第几天(1-31)
    public int getDayOfYear() 获取一年中的第几天(1-366)
    public DayOfWeek getDayOfWeek() 获取星期
    public int getMinute() 获取分钟
    public int getHour() 获取小时
  • 示例代码

    public class JDK8DateDemo3 {
          
          
        public static void main(String[] args) {
          
          
            LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 11, 11, 11, 20);
            //public int getYear()           获取年
            int year = localDateTime.getYear();
            System.out.println("年为" +year);
            //public int getMonthValue()     获取月份(1-12)
            int month = localDateTime.getMonthValue();
            System.out.println("月份为" + month);
    
            Month month1 = localDateTime.getMonth();
    //        System.out.println(month1);
    
            //public int getDayOfMonth()     获取月份中的第几天(1-31)
            int day = localDateTime.getDayOfMonth();
            System.out.println("日期为" + day);
    
            //public int getDayOfYear()      获取一年中的第几天(1-366)
            int dayOfYear = localDateTime.getDayOfYear();
            System.out.println("这是一年中的第" + dayOfYear + "天");
    
            //public DayOfWeek getDayOfWeek()获取星期
            DayOfWeek dayOfWeek = localDateTime.getDayOfWeek();
            System.out.println("星期为" + dayOfWeek);
    
            //public int getMinute()        获取分钟
            int minute = localDateTime.getMinute();
            System.out.println("分钟为" + minute);
            //public int getHour()           获取小时
      
            int hour = localDateTime.getHour();
            System.out.println("小时为" + hour);
        }
    }
    

12.4 LocalDateTime转换方法 (应用)

  • 方法说明

    方法名 说明
    public LocalDate toLocalDate () 转换成为一个LocalDate对象
    public LocalTime toLocalTime () 转换成为一个LocalTime对象
  • 示例代码

    public class JDK8DateDemo4 {
          
          
        public static void main(String[] args) {
          
          
            LocalDateTime localDateTime = LocalDateTime.of(2020, 12, 12, 8, 10, 12);
            //public LocalDate toLocalDate ()    转换成为一个LocalDate对象
            LocalDate localDate = localDateTime.toLocalDate();
            System.out.println(localDate);
    
            //public LocalTime toLocalTime ()    转换成为一个LocalTime对象
            LocalTime localTime = localDateTime.toLocalTime();
            System.out.println(localTime);
        }
    }
    

12.5 LocalDateTime格式化和解析 (应用)

  • 方法说明

    方法名 说明
    public String format (指定格式) 把一个LocalDateTime格式化成为一个字符串
    public LocalDateTime parse (准备解析的字符串, 解析格式) 把一个日期字符串解析成为一个LocalDateTime对象
    public static DateTimeFormatter ofPattern(String pattern) 使用指定的日期模板获取一个日期格式化器DateTimeFormatter对象
  • 示例代码

    public class JDK8DateDemo5 {
          
          
        public static void main(String[] args) {
          
          
            //method1();
            //method2();
        }
    
        private static void method2() {
          
          
            //public static LocalDateTime parse (准备解析的字符串, 解析格式) 把一个日期字符串解析成为一个LocalDateTime对象
            String s = "2020年11月12日 13:14:15";
            DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
            LocalDateTime parse = LocalDateTime.parse(s, pattern);
            System.out.println(parse);
        }
    
        private static void method1() {
          
          
            LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 12, 13, 14, 15);
            System.out.println(localDateTime);
            //public String format (指定格式)   把一个LocalDateTime格式化成为一个字符串
            DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
            String s = localDateTime.format(pattern);
            System.out.println(s);
        }
    }
    

12.6 LocalDateTime增加或者减少时间的方法 (应用)

  • 方法说明

    方法名 说明
    public LocalDateTime plusYears (long years) 添加或者减去年
    public LocalDateTime plusMonths(long months) 添加或者减去月
    public LocalDateTime plusDays(long days) 添加或者减去日
    public LocalDateTime plusHours(long hours) 添加或者减去时
    public LocalDateTime plusMinutes(long minutes) 添加或者减去分
    public LocalDateTime plusSeconds(long seconds) 添加或者减去秒
    public LocalDateTime plusWeeks(long weeks) 添加或者减去周
  • 示例代码

    /**
     * JDK8 时间类添加或者减去时间的方法
     */
    public class JDK8DateDemo6 {
          
          
        public static void main(String[] args) {
          
          
            //public LocalDateTime plusYears (long years)   添加或者减去年
    
            LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 11, 13, 14, 15);
            //LocalDateTime newLocalDateTime = localDateTime.plusYears(1);
            //System.out.println(newLocalDateTime);
    
              LocalDateTime newLocalDateTime = localDateTime.plusYears(-1);
            System.out.println(newLocalDateTime);
        }
    }
    
    

12.7 LocalDateTime减少或者增加时间的方法 (应用)

  • 方法说明

    方法名 说明
    public LocalDateTime minusYears (long years) 减去或者添加年
    public LocalDateTime minusMonths(long months) 减去或者添加月
    public LocalDateTime minusDays(long days) 减去或者添加日
    public LocalDateTime minusHours(long hours) 减去或者添加时
    public LocalDateTime minusMinutes(long minutes) 减去或者添加分
    public LocalDateTime minusSeconds(long seconds) 减去或者添加秒
    public LocalDateTime minusWeeks(long weeks) 减去或者添加周
  • 示例代码

    /**
     * JDK8 时间类减少或者添加时间的方法
     */
    public class JDK8DateDemo7 {
          
          
        public static void main(String[] args) {
          
          
            //public LocalDateTime minusYears (long years)  减去或者添加年
            LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 11, 13, 14, 15);
            //LocalDateTime newLocalDateTime = localDateTime.minusYears(1);
            //System.out.println(newLocalDateTime);
    
            LocalDateTime newLocalDateTime = localDateTime.minusYears(-1);
            System.out.println(newLocalDateTime);
    
        }
    }
    
    

12.8 LocalDateTime修改方法 (应用)

  • 方法说明

    方法名 说明
    public LocalDateTime withYear(int year) 直接修改年
    public LocalDateTime withMonth(int month) 直接修改月
    public LocalDateTime withDayOfMonth(int dayofmonth) 直接修改日期(一个月中的第几天)
    public LocalDateTime withDayOfYear(int dayOfYear) 直接修改日期(一年中的第几天)
    public LocalDateTime withHour(int hour) 直接修改小时
    public LocalDateTime withMinute(int minute) 直接修改分钟
    public LocalDateTime withSecond(int second) 直接修改秒
  • 示例代码

    /**
     * JDK8 时间类修改时间
     */
    public class JDK8DateDemo8 {
          
          
        public static void main(String[] args) {
          
          
            //public LocalDateTime withYear(int year)   修改年
            LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 11, 13, 14, 15);
           // LocalDateTime newLocalDateTime = localDateTime.withYear(2048);
           // System.out.println(newLocalDateTime);
    
            LocalDateTime newLocalDateTime = localDateTime.withMonth(20);
            System.out.println(newLocalDateTime);
    
        }
    }
    
    

12.9 Period (应用)

  • 方法说明

    方法名 说明
    public static Period between(开始时间,结束时间) 计算两个“时间"的间隔
    public int getYears() 获得这段时间的年数
    public int getMonths() 获得此期间的总月数
    public int getDays() 获得此期间的天数
    public long toTotalMonths() 获取此期间的总月数
  • 示例代码

    /**
     *  计算两个时间的间隔
     */
    public class JDK8DateDemo9 {
          
          
        public static void main(String[] args) {
          
          
            //public static Period between(开始时间,结束时间)  计算两个"时间"的间隔
    
            LocalDate localDate1 = LocalDate.of(2020, 1, 1);
            LocalDate localDate2 = LocalDate.of(2048, 12, 12);
            Period period = Period.between(localDate1, localDate2);
            System.out.println(period);//P28Y11M11D
    
            //public int getYears()         获得这段时间的年数
            System.out.println(period.getYears());//28
            //public int getMonths()        获得此期间的月数
            System.out.println(period.getMonths());//11
            //public int getDays()          获得此期间的天数
            System.out.println(period.getDays());//11
    
            //public long toTotalMonths()   获取此期间的总月数
            System.out.println(period.toTotalMonths());//347
    
        }
    }
    
    

12.10 Duration (应用)

  • 方法说明

    方法名 说明
    public static Durationbetween(开始时间,结束时间) 计算两个“时间"的间隔
    public long toSeconds() 获得此时间间隔的秒
    public int toMillis() 获得此时间间隔的毫秒
    public int toNanos() 获得此时间间隔的纳秒
  • 示例代码

    /**
     *  计算两个时间的间隔
     */
    public class JDK8DateDemo10 {
          
          
        public static void main(String[] args) {
          
          
            //public static Duration between(开始时间,结束时间)  计算两个“时间"的间隔
    
            LocalDateTime localDateTime1 = LocalDateTime.of(2020, 1, 1, 13, 14, 15);
            LocalDateTime localDateTime2 = LocalDateTime.of(2020, 1, 2, 11, 12, 13);
            Duration duration = Duration.between(localDateTime1, localDateTime2);
            System.out.println(duration);//PT21H57M58S
            //public long toSeconds()        获得此时间间隔的秒
            System.out.println(duration.toSeconds());//79078
            //public int toMillis()            获得此时间间隔的毫秒
            System.out.println(duration.toMillis());//79078000
            //public int toNanos()             获得此时间间隔的纳秒
            System.out.println(duration.toNanos());//79078000000000
        }
    }
    
    

练习

Instant instant = Instant.now();
System.out.println("当前时间戳是:"+instant); // 事实上Instant就是类似JDK8以前的Date
// 获取当前时间信息
LocalDateTime now = LocalDateTime.now(); //  表示时间+ 日期 (年月日时分秒)=》2023-02-26T23:17:42.734
int hour = now.getHour(); // 获取月份 =》 23 

// 获取指定时间信息
LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 11, 11, 11, 11);

// Date与LocalDateTime的相互转换
//将Date对象转换为LocalDateTime
Date date = new Date();
Instant instant = date.toInstant();
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
//将LocalDateTime对象转换为Date对象
LocalDateTime dateTime = LocalDateTime.now();
ZonedDateTime zonedDateTime = dateTime.atZone(ZoneId.systemDefault());
Instant instant2 = zonedDateTime.toInstant();
Date date2 = Date.from(instant2);

// 转换
LocalDate localDate = now.toLocalDate(); // 表示日期(年月日)  =》2023-02-26
LocalTime localTime = now.toLocalTime(); // 表示时间(时分秒)=》23:24:14.971

// 格式化 字符串<=>localDataTime
//public String format (指定格式)   把一个LocalDateTime格式化成为一个字符串
LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 12, 13, 14, 15);
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
String s = localDateTime.format(pattern); // 2020年11月12日 13:14:15
System.out.println(s);
//public static LocalDateTime parse (准备解析的字符串, 解析格式) 把一个日期字符串解析成为一个LocalDateTime对象
String s = "2020年11月12日 13:14:15";
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
LocalDateTime parse = LocalDateTime.parse(s, pattern); // 2020-11-12T13:14:15
System.out.println(parse);

// 获取新的时间 =》 添加/减少时间,修改时间
LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 11, 11, 11, 11);
LocalDateTime newLocalDateTime = localDateTime.minusYears(-1); // 减去一年,就是下一年 =》  2021-11-11T11:11:11
LocalDateTime newLocalDateTime2 = localDateTime.minusMonths(1); // 加上一月就是上一月 =》  2020-10-11T11:11:11
LocalDateTime newLocalDateTime3 = localDateTime.withMonth(1); // 设置成一月 =》  2020-01-11T11:11:11

// 计算两个时间间隔 =》 Duration
LocalDate localDate1 = LocalDate.of(2020, 1, 1);
LocalDate localDate2 = LocalDate.of(2048, 12, 12);
Period period = Period.between(localDate1, localDate2);//P28Y11M11D
System.out.println(period.getYears());// 获得这段时间的年数 => 28
System.out.println(period.getMonths());//获得此期间的月数 => 11
System.out.println(period.getDays());// 获得此期间的天数 => 11
// 计算两个日期间隔 =》 Period
LocalDateTime localDateTime1 = LocalDateTime.of(2020, 1, 1, 13, 14, 15);
LocalDateTime localDateTime2 = LocalDateTime.of(2020, 1, 2, 11, 12, 13);
Duration duration = Duration.between(localDateTime1, localDateTime2);//PT21H57M58S
System.out.println(duration.toMillis());// 获得此时间间隔的毫秒 => 79078000
System.out.println(duration.toNanos());// 获得此时间间隔的纳秒 => 79078000000000

猜你喜欢

转载自blog.csdn.net/weixin_44797182/article/details/130290437