第 11 章常用类

第 11 章常用类

11.7 Math 类

11.7.1 基本介绍

Math 类包含用于执行基本数学运算的方法,如初等指数、对数、平方根和三角函数。

11.7.2 方法一览(均为静态方法)

方法声明 功能说明
static double abs(double a) 返回 double 值的绝对值。
static float abs(float a) 返回 float 值的绝对值。
static int abs(int a) 返回 int 值的绝对值。
static long abs(long a) 返回 long 值的绝对值。
static double acos(double a) 返回一个值的反余弦;返回的角度范围在 0.0pi 之间。
static double asin(double a) 返回一个值的反正弦;返回的角度范围在 -pi/2pi/2 之间。
static double atan(double a) 返回一个值的反正切;返回的角度范围在 -pi/2pi/2 之间。
static double atan2(double y, double x) 将矩形坐标 (x, y) 转换成极坐标 (r, theta),返回所得角 theta
static double cbrt(double a) 返回 double 值的立方根。
static double ceil(double a) 返回大于或等于参数的最小整数(double 类型)。

11.7.3 Math 类常见方法应用案例

public class MathMethod {
    public static void main(String[] args) {
        //看看Math常用的方法(静态方法)
        //1.abs 绝对值
        int abs = Math.abs(-9);
        System.out.println(abs);//9
        //2.pow 求幂
        double pow = Math.pow(2, 4);//2的4次方
        System.out.println(pow);//16
        //3.ceil 向上取整,返回>=该参数的最小整数(转成double);
        double ceil = Math.ceil(3.9);
        System.out.println(ceil);//4.0
        //4.floor 向下取整,返回<=该参数的最大整数(转成double)
        double floor = Math.floor(4.001);
        System.out.println(floor);//4.0
        //5.round 四舍五入  Math.floor(该参数+0.5)
        long round = Math.round(5.51);
        System.out.println(round);//6
        //6.sqrt 求开方
        double sqrt = Math.sqrt(9.0);
        System.out.println(sqrt);//3.0

        //7.random 求随机数
        //  random 返回的是 0 <= x < 1 之间的一个随机小数
        // 思考:请写出获取 a-b之间的一个随机整数,a,b均为整数 ,比如 a = 2, b=7
        //  即返回一个数 x  2 <= x <= 7
        // 解读 Math.random() * (b-a) 返回的就是 0  <= 数 <= b-a
        // (1) (int)(a) <= x <= (int)(a + Math.random() * (b-a +1) )
        // (2) 使用具体的数给小伙伴介绍 a = 2  b = 7
        //  (int)(a + Math.random() * (b-a +1) ) = (int)( 2 + Math.random()*6)
        //  Math.random()*6 返回的是 0 <= x < 6 小数
        //  2 + Math.random()*6 返回的就是 2<= x < 8 小数
        //  (int)(2 + Math.random()*6) = 2 <= x <= 7
        // (3) 公式就是  (int)(a + Math.random() * (b-a +1) )
        for(int i = 0; i < 100; i++) {
            System.out.println((int)(2 +  Math.random() * (7 - 2 + 1)));
        }

        //max , min 返回最大值和最小值
        int min = Math.min(1, 9);
        int max = Math.max(45, 90);
        System.out.println("min=" + min);
        System.out.println("max=" + max);

    }
}

11.8 Arrays 类

11.8.1 Arrays 类常见方法应用案例

ArraysMethod01.java
Arrays 里面包含了一系列静态方法,用于管理或操作数组(比如排序和搜索)

  1. toString 返回数组的字符串形式
    Arrays.toString(arr)

  2. sort 排序(自然排序和定制排序)
    Integer arr[] = {1, -1, 7, 0, 89};
    ArraysSortCustom.java

  3. binarySearch 通过二分搜索法进行查找,要求必须排好序
    int index = Arrays.binarySearch(arr, 3);
    ArraysMethod02.java

  4. copyOf 数组元素的复制
    Integer[] newArr = Arrays.copyOf(arr, arr.length);

  5. fill 数组元素的填充
    Integer[] num = new Integer[]{9,3,2};
    Arrays.fill(num, 99);

  6. equals 比较两个数组元素内容是否完全一致
    boolean equals = Arrays.equals(arr, arr2);

  7. asList 将一组值,转换成 list
    List<Integer> asList = Arrays.asList(2,3,4,5,6,1);
    System.out.println("asList= " + asList);

public class ArraysMethod01 {
    public static void main(String[] args) {

        Integer[] integers = {1, 20, 90};
        //遍历数组
//        for(int i = 0; i < integers.length; i++) {
//            System.out.println(integers[i]);
//        }
        //直接使用Arrays.toString方法,显示数组
//        System.out.println(Arrays.toString(integers));//

        //演示 sort方法的使用

        Integer arr[] = {1, -1, 7, 0, 89};
        //进行排序
        //解读
        //1. 可以直接使用冒泡排序 , 也可以直接使用Arrays提供的sort方法排序
        //2. 因为数组是引用类型,所以通过sort排序后,会直接影响到 实参 arr
        //3. sort重载的,也可以通过传入一个接口 Comparator 实现定制排序
        //4. 调用 定制排序 时,传入两个参数 (1) 排序的数组 arr
        //   (2) 实现了Comparator接口的匿名内部类 , 要求实现  compare方法
        //5. 先演示效果,再解释
        //6. 这里体现了接口编程的方式 , 看看源码,就明白
        //   源码分析
        //(1) Arrays.sort(arr, new Comparator()
        //(2) 最终到 TimSort类的 private static <T> void binarySort(T[] a, int lo, int hi, int start,
        //                                       Comparator<? super T> c)()
        //(3) 执行到 binarySort方法的代码, 会根据动态绑定机制 c.compare()执行我们传入的
        //    匿名内部类的 compare ()
        //     while (left < right) {
        //                int mid = (left + right) >>> 1;
        //                if (c.compare(pivot, a[mid]) < 0)
        //                    right = mid;
        //                else
        //                    left = mid + 1;
        //            }
        //(4) new Comparator() {
        //            @Override
        //            public int compare(Object o1, Object o2) {
        //                Integer i1 = (Integer) o1;
        //                Integer i2 = (Integer) o2;
        //                return i2 - i1;
        //            }
        //        }
        //(5) public int compare(Object o1, Object o2) 返回的值>0 还是 <0
        //    会影响整个排序结果, 这就充分体现了 接口编程+动态绑定+匿名内部类的综合使用
        //    将来的底层框架和源码的使用方式,会非常常见
        //Arrays.sort(arr); // 默认排序方法
        //定制排序
        Arrays.sort(arr, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                Integer i1 = (Integer) o1;
                Integer i2 = (Integer) o2;
                return i2 - i1;
            }
        });
        System.out.println("===排序后===");
        System.out.println(Arrays.toString(arr));//



    }
}
public class ArraysMethod02 {
    public static void main(String[] args) {
        Integer[] arr = {1, 2, 90, 123, 567};
        // binarySearch 通过二分搜索法进行查找,要求必须排好
        // 解读
        //1. 使用 binarySearch 二叉查找
        //2. 要求该数组是有序的. 如果该数组是无序的,不能使用binarySearch
        //3. 如果数组中不存在该元素,就返回 return -(low + 1);  // key not found.
        int index = Arrays.binarySearch(arr, 567);
        System.out.println("index=" + index);

        //copyOf 数组元素的复制
        // 解读
        //1. 从 arr 数组中,拷贝 arr.length个元素到 newArr数组中
        //2. 如果拷贝的长度 > arr.length 就在新数组的后面 增加 null
        //3. 如果拷贝长度 < 0 就抛出异常NegativeArraySizeException
        //4. 该方法的底层使用的是 System.arraycopy()
        Integer[] newArr = Arrays.copyOf(arr, arr.length);
        System.out.println("==拷贝执行完毕后==");
        System.out.println(Arrays.toString(newArr));

        //ill 数组元素的填充
        Integer[] num = new Integer[]{9,3,2};
        //解读
        //1. 使用 99 去填充 num数组,可以理解成是替换原理的元素
        Arrays.fill(num, 99);
        System.out.println("==num数组填充后==");
        System.out.println(Arrays.toString(num));

        //equals 比较两个数组元素内容是否完全一致
        Integer[] arr2 = {1, 2, 90, 123};
        //解读
        //1. 如果arr 和 arr2 数组的元素一样,则方法true;
        //2. 如果不是完全一样,就返回 false
        boolean equals = Arrays.equals(arr, arr2);
        System.out.println("equals=" + equals);

        //asList 将一组值,转换成list
        //解读
        //1. asList方法,会将 (2,3,4,5,6,1)数据转成一个List集合
        //2. 返回的 asList 编译类型 List(接口)
        //3. asList 运行类型 java.util.Arrays#ArrayList, 是Arrays类的
        //   静态内部类 private static class ArrayList<E> extends AbstractList<E>
        //              implements RandomAccess, java.io.Serializable
        List asList = Arrays.asList(2,3,4,5,6,1);
        System.out.println("asList=" + asList);
        System.out.println("asList的运行类型" + asList.getClass());



    }
}

11.8.2 Arrays 类课堂练习

ArrayExercise.java
案例: 自定义Book类,里面包含nameprice,按price排序(从大到小)。要求使用两种方式排序,有一个 Book[] books = 4本书对象.

使用前面学习过的传递 实现Comparator接口匿名内部类,也称为定制排序。,可以按照
(1)price从大到小 (2)price从小到大 (3) 书名长度从大到小

Book[] books = new Book[4];  
books[0] = new Book("红楼梦", 100);  
books[1] = new Book("金梅新", 90);  
books[2] = new Book("青年文摘20年", 5);  
books[3] = new Book("java从入门到放弃~", 300);  
public class ArrayExercise {
    public static void main(String[] args) {
        /*
        案例:自定义Book类,里面包含name和price,按price排序(从大到小)。
        要求使用两种方式排序 , 有一个 Book[] books = 4本书对象.

        使用前面学习过的传递 实现Comparator接口匿名内部类,也称为定制排序。
        可以按照 price (1)从大到小 (2)从小到大 (3) 按照书名长度从大到小

         */

        Book[] books = new Book[4];
        books[0] = new Book("红楼梦", 100);
        books[1] = new Book("金梅新", 90);
        books[2] = new Book("青年文摘20年", 5);
        books[3] = new Book("java从入门到放弃~", 300);

        //(1)price从大到小

//        Arrays.sort(books, new Comparator() {
//            //这里是对Book数组排序,因此  o1 和 o2 就是Book对象
//            @Override
//            public int compare(Object o1, Object o2) {
//                Book book1 = (Book) o1;
//                Book book2 = (Book) o2;
//                double priceVal = book2.getPrice() - book1.getPrice();
//                //这里进行了一个转换
//                //如果发现返回结果和我们输出的不一致,就修改一下返回的 1 和 -1
//                if(priceVal > 0) {
//                    return  1;
//                } else  if(priceVal < 0) {
//                    return -1;
//                } else {
//                    return 0;
//                }
//            }
//        });

        //(2)price从小到大
//        Arrays.sort(books, new Comparator() {
//            //这里是对Book数组排序,因此  o1 和 o2 就是Book对象
//            @Override
//            public int compare(Object o1, Object o2) {
//                Book book1 = (Book) o1;
//                Book book2 = (Book) o2;
//                double priceVal = book2.getPrice() - book1.getPrice();
//                //这里进行了一个转换
//                //如果发现返回结果和我们输出的不一致,就修改一下返回的 1 和 -1
//                if(priceVal > 0) {
//                    return  -1;
//                } else  if(priceVal < 0) {
//                    return 1;
//                } else {
//                    return 0;
//                }
//            }
//        });

        //(3)按照书名长度从大到小

        Arrays.sort(books, new Comparator() {
            //这里是对Book数组排序,因此  o1 和 o2 就是Book对象
            @Override
            public int compare(Object o1, Object o2) {
                Book book1 = (Book) o1;
                Book book2 = (Book) o2;
                //要求按照书名的长度来进行排序
                return book2.getName().length() - book1.getName().length();
            }
        });


        System.out.println(Arrays.toString(books));

    }
}

class Book {
    private String name;
    private double price;

    public Book(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}

11.9 System 类

11.9.1 System 类常见方法和案例

  1. exit 退出当前程序
  2. arraycopy:复制数组元素,比较适合底层调用,一般使用 Arrays.copyOf 完成复制数组。
    int[] src={1,2,3};  
    int[] dest = new int[3];  
    System.arraycopy(src, 0, dest, 0, 3);  
    
  3. currentTimeMillis:返回当前时间距离 1970-1-1 的毫秒数
  4. gc:运行垃圾回收机制 System.gc();
public class System_ {
    public static void main(String[] args) {

        //exit 退出当前程序

//        System.out.println("ok1");
//        //解读
//        //1. exit(0) 表示程序退出
//        //2. 0 表示一个状态 , 正常的状态
//        System.exit(0);//
//        System.out.println("ok2");

        //arraycopy :复制数组元素,比较适合底层调用,
        // 一般使用Arrays.copyOf完成复制数组

        int[] src={1,2,3};
        int[] dest = new int[3];// dest 当前是 {0,0,0}

        //解读
        //1. 主要是搞清楚这五个参数的含义
        //2.
        //     源数组
        //     * @param      src      the source array.
        //     srcPos: 从源数组的哪个索引位置开始拷贝
        //     * @param      srcPos   starting position in the source array.
        //     dest : 目标数组,即把源数组的数据拷贝到哪个数组
        //     * @param      dest     the destination array.
        //     destPos: 把源数组的数据拷贝到 目标数组的哪个索引
        //     * @param      destPos  starting position in the destination data.
        //     length: 从源数组拷贝多少个数据到目标数组
        //     * @param      length   the number of array elements to be copied.
        System.arraycopy(src, 0, dest, 0, src.length);
        // int[] src={1,2,3};
        System.out.println("dest=" + Arrays.toString(dest));//[1, 2, 3]

        //currentTimeMillens:返回当前时间距离1970-1-1 的毫秒数
        // 解读:
        System.out.println(System.currentTimeMillis());
    }
}

11.10 BigInteger 和 BigDecimal 类

11.10.1 BigInteger 和 BigDecimal 介绍

应用场景:

  1. BigInteger 适合保存比较大的整型
  2. BigDecimal 适合保存精度更高的浮点型(小数)

11.10.2 BigInteger 和 BigDecimal 常见方法

BigInteger_java BigDecimal_java

  1. add
  2. subtract
  3. multiply
  4. divide
public class BigInteger_ {
    public static void main(String[] args) {

        //当我们编程中,需要处理很大的整数,long 不够用
        //可以使用BigInteger的类来搞定
//        long l = 23788888899999999999999999999l;
//        System.out.println("l=" + l);

        BigInteger bigInteger = new BigInteger("23788888899999999999999999999");
        BigInteger bigInteger2 = new BigInteger("10099999999999999999999999999999999999999999999999999999999999999999999999999999999");
        System.out.println(bigInteger);
        //解读
        //1. 在对 BigInteger 进行加减乘除的时候,需要使用对应的方法,不能直接进行 + - * /
        //2. 可以创建一个 要操作的 BigInteger 然后进行相应操作
        BigInteger add = bigInteger.add(bigInteger2);
        System.out.println(add);//
        BigInteger subtract = bigInteger.subtract(bigInteger2);
        System.out.println(subtract);//减
        BigInteger multiply = bigInteger.multiply(bigInteger2);
        System.out.println(multiply);//乘
        BigInteger divide = bigInteger.divide(bigInteger2);
        System.out.println(divide);//除


    }
}
public class BigDecimal_ {
    public static void main(String[] args) {
        //当我们需要保存一个精度很高的数时,double 不够用
        //可以是 BigDecimal
//        double d = 1999.11111111111999999999999977788d;
//        System.out.println(d);
        BigDecimal bigDecimal = new BigDecimal("1999.11");
        BigDecimal bigDecimal2 = new BigDecimal("3");
        System.out.println(bigDecimal);

        //解读
        //1. 如果对 BigDecimal进行运算,比如加减乘除,需要使用对应的方法
        //2. 创建一个需要操作的 BigDecimal 然后调用相应的方法即可
        System.out.println(bigDecimal.add(bigDecimal2));
        System.out.println(bigDecimal.subtract(bigDecimal2));
        System.out.println(bigDecimal.multiply(bigDecimal2));
        //System.out.println(bigDecimal.divide(bigDecimal2));//可能抛出异常ArithmeticException
        //在调用divide 方法时,指定精度即可. BigDecimal.ROUND_CEILING
        //如果有无限循环小数,就会保留 分子 的精度
        System.out.println(bigDecimal.divide(bigDecimal2, BigDecimal.ROUND_CEILING));
    }
}

11.11 日期类

11.11.1 第一代日期类

  1. Date:精确到毫秒,代表特定的瞬间
  2. SimpleDateFormat:格式和解析日期的类
    SimpleDateFormat 格式化和解析日期的具体类。它允许进行格式化(日期 -> 文本)、解析(文本 -> 日期)和规范化。
  3. 应用实例 Date_java

(右侧含日期或时间元素表示的表格,如 Era 标志符、年、年中的月份等对应表示和示例 )

public class Date01 {
    public static void main(String[] args) throws ParseException {

        //解读
        //1. 获取当前系统时间
        //2. 这里的Date 类是在java.util包
        //3. 默认输出的日期格式是国外的方式, 因此通常需要对格式进行转换
        Date d1 = new Date(); //获取当前系统时间
        System.out.println("当前日期=" + d1);
        Date d2 = new Date(9234567); //通过指定毫秒数得到时间
        System.out.println("d2=" + d2); //获取某个时间对应的毫秒数
//

        //解读
        //1. 创建 SimpleDateFormat对象,可以指定相应的格式
        //2. 这里的格式使用的字母是规定好,不能乱写

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss E");
        String format = sdf.format(d1); // format:将日期转换成指定格式的字符串
        System.out.println("当前日期=" + format);

        //解读
        //1. 可以把一个格式化的String 转成对应的 Date
        //2. 得到Date 仍然在输出时,还是按照国外的形式,如果希望指定格式输出,需要转换
        //3. 在把String -> Date , 使用的 sdf 格式需要和你给的String的格式一样,否则会抛出转换异常
        String s = "1996年01月01日 10:20:30 星期一";
        Date parse = sdf.parse(s);
        System.out.println("parse=" + sdf.format(parse));

    }
}

11.11.2 第二代日期类

  1. 第二代日期类,主要就是 Calendar 类(日历)。
    public abstract class Calendar extends Object implements Serializable, Cloneable, Comparable<Calendar>  
    
  2. Calendar 类是一个抽象类,它为特定瞬间与一组诸如 YEARMONTHDAY_OF_MONTHHOUR日历字段之间的转换提供了一些方法,并为操作日历字段(例如获得下星期的日期)提供了一些方法。
public class Calendar_ {
    public static void main(String[] args) {
        //解读
        //1. Calendar是一个抽象类, 并且构造器是private
        //2. 可以通过 getInstance() 来获取实例
        //3. 提供大量的方法和字段提供给程序员
        //4. Calendar没有提供对应的格式化的类,因此需要程序员自己组合来输出(灵活)
        //5. 如果我们需要按照 24小时进制来获取时间, Calendar.HOUR ==改成=> Calendar.HOUR_OF_DAY
        Calendar c = Calendar.getInstance(); //创建日历类对象//比较简单,自由
        System.out.println("c=" + c);
        //2.获取日历对象的某个日历字段
        System.out.println("年:" + c.get(Calendar.YEAR));
        // 这里为什么要 + 1, 因为Calendar 返回月时候,是按照 0 开始编号
        System.out.println("月:" + (c.get(Calendar.MONTH) + 1));
        System.out.println("日:" + c.get(Calendar.DAY_OF_MONTH));
        System.out.println("小时:" + c.get(Calendar.HOUR));
        System.out.println("分钟:" + c.get(Calendar.MINUTE));
        System.out.println("秒:" + c.get(Calendar.SECOND));
        //Calender 没有专门的格式化方法,所以需要程序员自己来组合显示
        System.out.println(c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.DAY_OF_MONTH) +
                " " + c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE) + ":" + c.get(Calendar.SECOND) );

    }
}

11.11.3 第三代日期类

前面两代日期类的不足分析
JDK 1.0中包含了一个java.util.Date类,但是它的大多数方法已经在JDK 1.1引入Calendar类之后被弃用了。而Calendar也存在问题是:

  1. 可变性:像日期和时间这样的类应该是不可变的。
  2. 偏移性:Date中的年份是从1900开始的,而月份都从0开始。
  3. 格式化:格式化只对Date有用,Calendar则不行。
  4. 此外,它们也不是线程安全的,不能处理闰秒等(每隔2天,多出1s)。

第三代日期类核心

  1. LocalDate(日期/年月日)、LocalTime(时间/时分秒)、LocalDateTime(日期时间/年月日时分秒) JDK8加入
    • LocalDate只包含日期,可以获取日期字段
    • LocalTime只包含时间,可以获取时间字段
    • LocalDateTime包含日期+时间,可以获取日期和时间字段
      案例演示:LocalDate_java
LocalDateTime ldt = LocalDateTime.now(); //LocalDate.now();//LocalTime.now()  
System.out.println(ldt);  
ldt.getYear();ldt.getMonthValue();ldt.getMonth();ldt.getDayOfMonth();  
ldt.getHour();ldt.getMinute();ldt.getSecond();  
public class LocalDate_ {
    public static void main(String[] args) {
        //第三代日期
        //解读
        //1. 使用now() 返回表示当前日期时间的 对象
        LocalDateTime ldt = LocalDateTime.now(); //LocalDate.now();//LocalTime.now()
        System.out.println(ldt);

        //2. 使用DateTimeFormatter 对象来进行格式化
        // 创建 DateTimeFormatter对象
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format = dateTimeFormatter.format(ldt);
        System.out.println("格式化的日期=" + format);

        System.out.println("年=" + ldt.getYear());
        System.out.println("月=" + ldt.getMonth());
        System.out.println("月=" + ldt.getMonthValue());
        System.out.println("日=" + ldt.getDayOfMonth());
        System.out.println("时=" + ldt.getHour());
        System.out.println("分=" + ldt.getMinute());
        System.out.println("秒=" + ldt.getSecond());

        LocalDate now = LocalDate.now(); //可以获取年月日
        LocalTime now2 = LocalTime.now();//获取到时分秒


        //提供 plus 和 minus方法可以对当前时间进行加或者减
        //看看890天后,是什么时候 把 年月日-时分秒
        LocalDateTime localDateTime = ldt.plusDays(890);
        System.out.println("890天后=" + dateTimeFormatter.format(localDateTime));

        //看看在 3456分钟前是什么时候,把 年月日-时分秒输出
        LocalDateTime localDateTime2 = ldt.minusMinutes(3456);
        System.out.println("3456分钟前 日期=" + dateTimeFormatter.format(localDateTime2));

    }
}

11.11.4 DateTimeFormatter 格式日期类

类似于SimpleDateFormat

DateTimeFormatter dtf = DateTimeFormatter.ofPattern(格式);  
String str = dtf.format(日期对象);  

案例演示:

LocalDateTime ldt = LocalDateTime.now();  
//关于 DateTimeFormatter 的各个格式参数,需要看jdk8的文档.  
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒");  
String strDate = dtf.format(ldt);  

11.11.5 Instant 时间戳

类似于Date,提供了一系列和Date类转换的方式

  • Instant --> Date:
    Date date = Date.from(instant);

  • Date --> Instant:
    Instant instant = date.toInstant();

案例演示:

Instant now = Instant.now();  
System.out.println(now);  
Date date = Date.from(now);  
Instant instant = date.toInstant();  
public class Instant_ {
    public static void main(String[] args) {

        //1.通过 静态方法 now() 获取表示当前时间戳的对象
        Instant now = Instant.now();
        System.out.println(now);
        //2. 通过 from 可以把 Instant转成 Date
        Date date = Date.from(now);
        //3. 通过 date的toInstant() 可以把 date 转成Instant对象
        Instant instant = date.toInstant();

    }
}

11.11.6 第三代日期类更多方法

  • LocalDateTime
  • MonthDay类:检查重复事件
  • 是否是闰年
  • 增加日期的某个部分
  • 使用plus方法测试增加时间的某个部分
  • 使用minus方法测试查看一年前和一年后的日期
  • 其他的方法,就不说,使用的时候,自己查看API使用即可

11.12 本章作业

1. 编程题 Homework01.java

(1) 将字符串中指定部分进行反转。比如将"abcdef"反转为"aedcbf"

(2) 编写方法 public static String reverse(String str, int start, int end) 搞定
以下是整理后的内容,按“同上”(延续之前的章节替换规则,把原 13 开头章节调整为 11 开头 )的格式呈现:

public class Homework01 {
    public static void main(String[] args) {
        //测试
        String str = "abcdef";
        System.out.println("===交换前===");
        System.out.println(str);
        try {
            str = reverse(str, -1, 4);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return;
        }
        System.out.println("===交换后===");
        System.out.println(str);
    }

    /**
     * (1) 将字符串中指定部分进行反转。比如将"abcdef"反转为"aedcbf"
     * (2) 编写方法 public static String reverse(String  str, int start , int end) 搞定
     * 思路分析
     * (1) 先把方法定义确定
     * (2) 把 String 转成 char[] ,因为char[] 的元素是可以交换的
     * (3) 画出分析示意图
     * (4) 代码实现
     */
    public static String reverse(String str, int start, int end) {


        //对输入的参数做一个验证
        //重要的编程技巧分享!!!
        //(1) 写出正确的情况
        //(2) 然后取反即可
        //(3) 这样写,你的思路就不乱
        if(!(str != null && start >= 0 && end > start && end < str.length())) {
            throw new RuntimeException("参数不正确");
        }

        char[] chars = str.toCharArray();
        char temp = ' '; //交换辅助变量
        for (int i = start, j = end; i < j; i++, j--) {
            temp = chars[i];
            chars[i] = chars[j];
            chars[j] = temp;
        }
        //使用chars 重新构建一个String 返回即可
        return new String(chars);

    }
}

2. 编程题 Homework02.java

输入用户名、密码、邮箱,如果信息录入正确,则提示注册成功,否则生成异常对象
要求:

  1. 用户名长度为2或3或4
  2. 密码的长度为6,要求全是数字(可用 isDigital 辅助判断 )
  3. 邮箱中包含@. ,并且@.的前面
public class Homework02 {
    public static void main(String[] args) {

        String name = "abc";
        String pwd = "123456";
        String email = "ti@i@sohu.com";

        try {
            userRegister(name,pwd,email);
            System.out.println("恭喜你,注册成功~");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }

    /**
     * 输入用户名、密码、邮箱,如果信息录入正确,则提示注册成功,否则生成异常对象
     * 要求:
     * (1) 用户名长度为2或3或4
     * (2) 密码的长度为6,要求全是数字  isDigital
     * (3) 邮箱中包含@和.   并且@在.的前面
     * <p>
     * 思路分析
     * (1) 先编写方法 userRegister(String name, String pwd, String email) {}
     * (2) 针对 输入的内容进行校核,如果发现有问题,就抛出异常,给出提示
     * (3) 单独的写一个方法,判断 密码是否全部是数字字符 boolean
     */
    public static void userRegister(String name, String pwd, String email) {

        //再加入一些校验
        if(!(name != null && pwd != null && email != null)) {
            throw  new RuntimeException("参数不能为null");
        }

        //过关
        //第一关
        int userLength = name.length();
        if (!(userLength >= 2 && userLength <= 4)) {
            throw new RuntimeException("用户名长度为2或3或4");
        }

        //第二关
        if (!(pwd.length() == 6 && isDigital(pwd))) {
            throw new RuntimeException("密码的长度为6,要求全是数字");
        }

        //第三关
        int i = email.indexOf('@');
        int j = email.indexOf('.');
        if (!(i > 0 && j > i)) {
            throw new RuntimeException("邮箱中包含@和.   并且@在.的前面");
        }


    }

    //单独的写一个方法,判断 密码是否全部是数字字符 boolean
    public static boolean isDigital(String str) {
        char[] chars = str.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] < '0' || chars[i] > '9') {
                return false;
            }
        }
        return true;
    }

}

3. 编程题 Homework03.java

  1. 编写Java程序,输入形式为:Han shun Ping 的人名,以 Ping,Han .S 的形式打印出来 。其中.S是中间单词的首字母。
  2. 例如输入“Willian Jefferson Clinton”,输出形式为:Clinton, Willian .J
public class Homework03 {
    public static void main(String[] args) {
        String name = "Willian Jefferson Clinton";
        printName(name);
    }

    /**
     * 编写方法: 完成输出格式要求的字符串
     * 编写java程序,输入形式为: Han shun Ping的人名,以Ping,Han .S的形式打印
     *       出来    。其中.S是中间单词的首字母
     * 思路分析
     * (1) 对输入的字符串进行 分割split(" ")
     * (2) 对得到的String[] 进行格式化String.format()
     * (3) 对输入的字符串进行校验即可
     */
    public static void printName(String str) {

        if(str == null) {
            System.out.println("str 不能为空");
            return;
        }

        String[] names = str.split(" ");
        if(names.length != 3) {
            System.out.println("输入的字符串格式不对");
            return;
        }

        String format = String.format("%s,%s .%c", names[2], names[0], names[1].toUpperCase().charAt(0));
        System.out.println(format);
    }
}

4. 编程题 Homework04.java

输入字符串,判断里面有多少个大写字母,多少个小写字母,多少个数字

public class Homework04 {
    public static void main(String[] args) {
            String str = "abcHsp U 1234";
            countStr(str);
    }

    /**
     * 输入字符串,判断里面有多少个大写字母,多少个小写字母,多少个数字
     * 思路分析
     * (1) 遍历字符串,如果 char 在 '0'~'9' 就是一个数字
     * (2) 如果 char 在 'a'~'z' 就是一个小写字母
     * (3) 如果 char 在 'A'~'Z' 就是一个大写字母
     * (4) 使用三个变量来记录 统计结果
     */
    public static void countStr(String str) {
        if (str == null) {
            System.out.println("输入不能为 null");
            return;
        }
        int strLen = str.length();
        int numCount = 0;
        int lowerCount = 0;
        int upperCount = 0;
        int otherCount = 0;
        for (int i = 0; i < strLen; i++) {
            if(str.charAt(i) >= '0' && str.charAt(i) <= '9') {
                numCount++;
            } else if(str.charAt(i) >= 'a' && str.charAt(i) <= 'z') {
                lowerCount++;
            } else if(str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') {
                upperCount++;
            } else {
                otherCount++;
            }
        }

        System.out.println("数字有 " + numCount);
        System.out.println("小写字母有 " + lowerCount);
        System.out.println("大写字母有 " + upperCount);
        System.out.println("其他字符有 " + otherCount);
    }
}
posted @ 2025-08-19 23:51  *珍惜当下*  阅读(13)  评论(0)    收藏  举报