总结

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
1:正则表达式(理解)
    (1)就是符合一定规则的字符串
    (2)常见规则
        A:字符
            x 字符 x举例'a'表示字符a
            \\ 反斜线字符
            \n 新行换行 ('\u000A') 
            \r 回车符 ('\u000D')

        B:字符类
            [abc] ab  c简单类 
            [^abc] 任何字符除了 ab  c否定 
            [a-zA-Z] a到 z  A到 Z两头的字母包括在内范围 
            [0-9] 0到9的字符都包括

        C:预定义字符类
            . 任何字符我的就是.字符本身怎么表示呢? \.
            \d 数字[0-9]
            \w 单词字符[a-zA-Z_0-9]
                在正则表达式里面组成单词的东西必须有这些东西组成

        D:边界匹配器
            ^ 行的开头 
            $ 行的结尾 
            \b 单词边界
                就是不是单词字符的地方
                举例hello world?haha;xixi

        E:Greedy 数量词 
            X? X一次或一次也没有
            X* X零次或多次
            X+ X一次或多次
            X{n} X恰好 n  
            X{n,} X至少 n  
            X{n,m} X至少 n 但是不超过 m  
    (3)常见功能(分别用的是谁呢?)
        A:判断功能
            String类的public boolean matches(String regex)
        B:分割功能
            String类的public String[] split(String regex)
        C:替换功能
            String类的public String replaceAll(String regex,String replacement)
        D:获取功能
            Pattern和Matcher
                Pattern p = Pattern.compile("a*b");
                Matcher m = p.matcher("aaaaab");

                find():查找存不存在
                group():获取刚才查找过的数据
    (4)案例
        A:判断电话号码和邮箱
        B:按照不同的规则分割数据
        C:把论坛中的数字替换为*
        D:获取字符串中由3个字符组成的单词

2:Math(掌握)
    (1)针对数学运算进行操作的类
    (2)常见方法(自己补齐)
        A:绝对值
        B:向上取整
        C:向下取整
        D:两个数据中的大值
        E:a的b次幂
        F:随机数
        G:四舍五入
        H:正平方根
    (3)案例
        A:猜数字小游戏
        B:获取任意范围的随机数

3:Random(理解)
    (1)用于产生随机数的类
    (2)构造方法:
        A:Random() 默认种子每次产生的随机数不同
        B:Random(long seed) 指定种子每次种子相同随机数就相同
    (3)成员方法:
        A:int nextInt() 返回int范围内的随机数
        B:int nextInt(int n) 返回[0,n)范围内的随机数

4:System(掌握)
    (1)系统类,提供了一些有用的字段和方法
    (2)成员方法(自己补齐)
        A:运行垃圾回收器
        B:退出jvm
        C:获取当前时间的毫秒值
        D:数组复制

5:BigInteger(理解)
    (1)针对大整数的运算
    (2)构造方法 
        A:BigInteger(String s)
    (3)成员方法(自己补齐)
        A:
        B:
        C:
        D:
        E:商和余数

6:BigDecimal(理解)
    (1)浮点数据做运算会丢失精度所以针对浮点数据的操作建议采用BigDecimal(金融相关的项目)
    (2)构造方法
        A:BigDecimal(String s)
    (3)成员方法
        A:
        B:
        C:
        D:
        E:自己保留小数几位

7:Date/DateFormat(掌握)
    (1)Date是日期类可以精确到毫秒
        A:构造方法
            Date()
            Date(long time)
        B:成员方法
            getTime()
            setTime(long time)
        C:日期和毫秒值的相互转换
        案例你来到这个世界多少天了?
    (2)DateFormat针对日期进行格式化和针对字符串进行解析的类但是是抽象类所以使用其子类SimpleDateFormat
        A:SimpleDateFormat(String pattern) 给定模式
            yyyy-MM-dd HH:mm:ss
        B:日期和字符串的转换
            a:Date -- String
                format()

            b:String -- Date
                parse()
        C:案例
            制作了一个针对日期操作的工具类

8:Calendar(掌握)
    (1)日历类封装了所有的日历字段值通过统一的方法根据传入不同的日历字段可以获取值
    (2)如何得到一个日历对象呢?
        Calendar rightNow = Calendar.getInstance();
        本质返回的是子类对象
    (3)成员方法
        A:根据日历字段得到对应的值
        B:根据日历字段和一个正负数确定是添加还是减去对应日历字段的值
        C:设置日历对象的年月日
    (4)案例
        计算任意一年的2月份有多少天?

正则表达式概述及基本使用

  • 正则表达式:是指一个用来描述或者匹配一系列符合某个句法规则的字符串的单个字符串。

其实就是一种规则。有自己特殊的应用。

  • 举例:校验qq号码.
  • 1:要求必须是5-15位数字

  • 2:0不能开头 代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package cn.itcast_01;

import java.util.Scanner;

/*
 * 校验qq号码.
 *      1:要求必须是5-15位数字
 *      2:0不能开头
 * 
 * 分析:
 *      A:键盘录入一个QQ号码
 *      B:写一个功能实现校验
 *      C:调用功能,输出结果。
 */
public class RegexDemo {
    public static void main(String[] args) {
        // 创建键盘录入对象
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入你的QQ号码:");
        String qq = sc.nextLine();

        System.out.println("checkQQ:"+checkQQ(qq));
    }

    /*
     * 写一个功能实现校验 两个明确: 明确返回值类型:boolean 明确参数列表:String qq
     */
    public static boolean checkQQ(String qq) {
        boolean flag = true;

        // 校验长度
        if (qq.length() >= 5 && qq.length() <= 15) {
            // 0不能开头
            if (!qq.startsWith("0")) {
                // 必须是数字
                char[] chs = qq.toCharArray();  //将字符串转换成字符数组挨个遍历
                for (int x = 0; x < chs.length; x++) {
                    char ch = chs[x];
                    if (!Character.isDigit(ch)) {
                        flag = false;
                        break;
                    }
                }
            } else {
                flag = false;
            }
        } else {
            flag = false;
        }

        return flag;
    }
}

执行结果:

1
2
3
4
5
6
7
请输入你的QQ号码
318977674
checkQQ:true
===========
请输入你的QQ号码
abc123
checkQQ:false

实例:使用正则表达式?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package cn.itcast_01;

import java.util.Scanner;

/*
 * 正则表达式:符合一定规则的字符串。
 */
public class RegexDemo2 {
    public static void main(String[] args) {
        // 创建键盘录入对象
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入你的QQ号码:");
        String qq = sc.nextLine();

        System.out.println("checkQQ:" + checkQQ(qq));
    }

    public static boolean checkQQ(String qq) {
        // String regex ="[1-9][0-9]{4,14}";
        // //public boolean matches(String regex)告知此字符串是否匹配给定的正则表达式
        // boolean flag = qq.matches(regex);
        // return flag;

        //return qq.matches("[1-9][0-9]{4,14}");

        return qq.matches("[1-9]\\d{4,14}"); //跟python类似
    }
}

正则表达式的组成规则

  • 规则字符在java.util.regex Pattern类中

  • 常见组成规则

​ • 字符

​ • 字符类

​ • 预定义字符类

​ • 边界匹配器

​ • 数量词 规则:::

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
A:字符
    x 字符 x举例'a'表示字符a
    \\ 反斜线字符 //对\进行转义
    \n 新行换行 ('\u000A') 
    \r 回车符 ('\u000D')

B:字符类
    [abc] ab  c简单类 
    [^abc] 任何字符除了 ab  c否定 
    [a-zA-Z] a到 z  A到 Z两头的字母包括在内范围 
    [0-9] 0到9的字符都包括

C:预定义字符类
    . 任何字符我的就是.字符本身怎么表示呢? \.
    \d 数字[0-9]
    \w 单词字符[a-zA-Z_0-9]
        在正则表达式里面组成单词的东西必须有这些东西组成

D:边界匹配器
    ^ 行的开头 
    $ 行的结尾 
    \b 单词边界
        就是不是单词字符的地方
        举例hello world?haha;xixi

E:Greedy 数量词 
    X? X一次或一次也没有
    X* X零次或多次
    X+ X一次或多次
    X{n} X恰好 n  
    X{n,} X至少 n  
    X{n,m} X至少 n 但是不超过 m  

正则表达式的应用

  • 判断功能

    • public boolean matches(String regex) 判断手机号是否满足要求

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package cn.itcast_02;

import java.util.Scanner;

/*
 * 判断功能
 *      String类的public boolean matches(String regex)
 *
 * 需求:
 *      判断手机号码是否满足要求?
 * 
 * 分析:
 *      A:键盘录入手机号码
 *      B:定义手机号码的规则
 *          13436975980
 *          13688886868
 *          13866668888
 *          13456789012
 *          13123456789
 *          18912345678
 *          18886867878
 *          18638833883
 *      C:调用功能,判断即可
 *      D:输出结果
 */
public class RegexDemo {
    public static void main(String[] args) {
        //键盘录入手机号码
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入你的手机号码:");
        String phone = sc.nextLine();

        //定义手机号码的规则
        String regex = "1[38]\\d{9}";

        //调用功能,判断即可
        boolean flag = phone.matches(regex);

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

执行:

1
2
3
请输入你的手机号码
18824825277
flag:true

例子:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package cn.itcast_02;

import java.util.Scanner;

/*
 * 校验邮箱
 * 
 * 分析:
 *      A:键盘录入邮箱
 *      B:定义邮箱的规则
 *          1517806580@qq.com
 *          liuyi@163.com
 *          linqingxia@126.com
 *          fengqingyang@sina.com.cn
 *          fqy@itcast.cn
 *      C:调用功能,判断即可
 *      D:输出结果
 */
public class RegexTest {
    public static void main(String[] args) {
        //键盘录入邮箱
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入邮箱:");
        String email = sc.nextLine();

        //定义邮箱的规则
        //String regex = "[a-zA-Z_0-9]+@[a-zA-Z_0-9]{2,6}(\\.[a-zA-Z_0-9]{2,3})+";
        String regex = "\\w+@\\w{2,6}(\\.\\w{2,3})+";

        //调用功能,判断即可
        boolean flag = email.matches(regex);

        //输出结果
        System.out.println("flag:"+flag);
    }
}
  • 分割功能

    • public String[] split(String regex)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package cn.itcast_03;

import java.util.Scanner;

/*
 * 分割功能
 *      String类的public String[] split(String regex)
 *      根据给定正则表达式的匹配拆分此字符串。 
 *
 * 举例:
 *      百合网,世纪佳缘,珍爱网,QQ
 *      搜索好友
 *          性别:女
 *          范围:"18-24"
 * 
 *      age>=18 && age<=24
 */
public class RegexDemo {
    public static void main(String[] args) {
        //定义一个年龄搜索范围
        String ages = "18-24";

        //定义规则
        String regex = "-";

        //调用方法
        String[] strArray = ages.split(regex); //字符数组,以-进行分割

//      //遍历
//      for(int x=0; x<strArray.length; x++){
//          System.out.println(strArray[x]);
//      }

        //如何得到int类型的呢?
        int startAge = Integer.parseInt(strArray[0]);
        int endAge = Integer.parseInt(strArray[1]);

        //键盘录入年龄
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入你的年龄:");
        int age = sc.nextInt();

        if(age>=startAge && age<=endAge) {
            System.out.println("你就是我想找的");
        }else {
            System.out.println("不符合我的要求,gun");
        }
    }
}

执行:

1
2
3
请输入你的年龄
18
你就是我想找的

实例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package cn.itcast_03;

/*
 * 分割功能练习
 */
public class RegexDemo2 {
    public static void main(String[] args) {
        // 定义一个字符串
        String s1 = "aa,bb,cc";
        // 直接分割
        String[] str1Array = s1.split(",");
        for (int x = 0; x < str1Array.length; x++) {
            System.out.println(str1Array[x]);
        }
        System.out.println("---------------------");

        String s2 = "aa.bb.cc";
        String[] str2Array = s2.split("\\.");
        for (int x = 0; x < str2Array.length; x++) {
            System.out.println(str2Array[x]);
        }
        System.out.println("---------------------");

        String s3 = "aa    bb                cc";
        String[] str3Array = s3.split(" +"); //空格一次以上
        for (int x = 0; x < str3Array.length; x++) {
            System.out.println(str3Array[x]);
        }
        System.out.println("---------------------");

        //硬盘上的路径,我们应该用\\替代\
        String s4 = "E:\\JavaSE\\day14\\avi";
        String[] str4Array = s4.split("\\\\");
        for (int x = 0; x < str4Array.length; x++) {
            System.out.println(str4Array[x]);
        }
        System.out.println("---------------------");
    }
}

执行

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
aa
bb
cc
---------------------
aa
bb
cc
---------------------
aa
bb
cc
---------------------
E:
JavaSE
day14
avi
---------------------

案例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package cn.itcast_03;

import java.util.Arrays;

/*
 * 我有如下一个字符串:"91 27 46 38 50"
 * 请写代码实现最终输出结果是:"27 38 46 50 91"
 * 
 * 分析:
 *      A:定义一个字符串
 *      B:把字符串进行分割,得到一个字符串数组
 *      C:把字符串数组变换成int数组
 *      D:对int数组排序
 *      E:把排序后的int数组在组装成一个字符串
 *      F:输出字符串
 */
public class RegexTest {
    public static void main(String[] args) {
        // 定义一个字符串
        String s = "91 27 46 38 50"; // 定义一个字符串

        // 把字符串进行分割,得到一个字符串数组
        String[] strArray = s.split(" ");

        // 把字符串数组变换成int数组
        int[] arr = new int[strArray.length];

        for (int x = 0; x < arr.length; x++) {
            arr[x] = Integer.parseInt(strArray[x]);
        }

        // 对int数组排序
        Arrays.sort(arr);

        // 把排序后的int数组在组装成一个字符串
        StringBuilder sb = new StringBuilder();
        for (int x = 0; x < arr.length; x++) {
            sb.append(arr[x]).append(" ");
        }
        // 转化为字符串(字符数组转换成字符串)
        String result = sb.toString().trim();// 转换成字符串并去掉前后的空格

        // 输出字符串
        System.out.println("result:" + result);
    }
}
  • 替换功能

    • public String replaceAll(String regex,String replacement)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package cn.itcast_04;

/*
 * 替换功能
 *      String类的public String replaceAll(String regex,String replacement)
 *      使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串。 
 */
public class RegexDemo {
    public static void main(String[] args) {
        // 定义一个字符串
        String s = "helloqq12345worldkh622112345678java";

        // 我要去除所有的数字,用*给替换掉
        // String regex = "\\d+";  //连续的数字给一颗*
        // String regex = "\\d"; //出现数字就给一个*
        // String ss = "*";

        // 直接把数字干掉
        String regex = "\\d+";
        String ss = "";

        String result = s.replaceAll(regex, ss);

        System.out.println(result);
    }
}
  • 获取功能

    • Pattern和Matcher类的使用 基本使用的顺讯

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package cn.itcast_05;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/*
 * 获取功能
 *      Pattern和Matcher类的使用
 *      
 *      模式和匹配器的基本使用顺序
 */
public class RegexDemo {
    public static void main(String[] args) {
        // 模式和匹配器的典型调用顺序
        // 把正则表达式编译成模式对象
        Pattern p = Pattern.compile("a*b");
        // 通过模式对象得到匹配器对象,这个时候需要的是被匹配的字符串
        Matcher m = p.matcher("aaaaab");
        // 调用匹配器对象的功能
        boolean b = m.matches();
        System.out.println(b);

        //这个是判断功能,但是如果做判断,这样做就有点麻烦了,我们直接用字符串的方法做
        String s = "aaaaab";
        String regex = "a*b";
        boolean bb = s.matches(regex);
        System.out.println(bb);
    }
}

实例获取功能

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package cn.itcast_05;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/*
 * 获取功能:
 * 获取下面这个字符串中由三个字符组成的单词
 * da jia ting wo shuo,jin tian yao xia yu,bu shang wan zi xi,gao xing bu?
 */
public class RegexDemo2 {
    public static void main(String[] args) {
        // 定义字符串
        String s = "da jia ting wo shuo,jin tian yao xia yu,bu shang wan zi xi,gao xing bu?";
        // 规则
        String regex = "\\b\\w{3}\\b";  // \b是单词边界

        // 把规则编译成模式对象
        Pattern p = Pattern.compile(regex);
        // 通过模式对象得到匹配器对象
        Matcher m = p.matcher(s);
        // 调用匹配器对象的功能
        // 通过find方法就是查找有没有满足条件的子串
        // public boolean find()
        // boolean flag = m.find();
        // System.out.println(flag);
        // // 如何得到值呢?
        // // public String group()
        // String ss = m.group();
        // System.out.println(ss);
        //
        // // 再来一次
        // flag = m.find();
        // System.out.println(flag);
        // ss = m.group();
        // System.out.println(ss);

        while (m.find()) {
            System.out.println(m.group());
        }

        // 注意:一定要先find(),然后才能group()
        // IllegalStateException: No match found
        // String ss = m.group();
        // System.out.println(ss);
    }
}

结果

1
2
3
4
5
6
jia
jin
yao
xia
wan
gao

正则表达式的练习(前面都有了)

  • 判断功能:

    • 校验邮箱

  • 分割功能:

    • 我有如下一个字符串:”91 27 46 38 50”

    • 请写代码实现最终输出结果是:”27 38 46 50 91”

  • 替换功能:

    • 论坛中不能出现数字字符,用*替换

  • 获取功能:

    • 获取由三个字符组成的单词

**Math**类概述及其成员方法

  • Math类概述

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

  • 成员方法

    • public static int abs(int a)

    • public static double ceil(double a)

    • public static double floor(double a)

    • public static int max(int a,int b) min自学

    • public static double pow(double a,double b)

    • public static double random()

    • public static int round(float a) 参数为double的自学

    • public static double sqrt(double a)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package cn.itcast_01;

/*
 * Math:用于数学运算的类。
 * 成员变量:
 *      public static final double PI
 *      public static final double E
 * 成员方法:
 *      public static int abs(int a):绝对值
 *      public static double ceil(double a):向上取整
 *      public static double floor(double a):向下取整
 *      public static int max(int a,int b):最大值 (min自学)
 *      public static double pow(double a,double b):a的b次幂
 *      public static double random():随机数 [0.0,1.0)
 *      public static int round(float a) 四舍五入(参数为double的自学)
 *      public static double sqrt(double a):正平方根
 */
public class MathDemo {
    public static void main(String[] args) {
        // public static final double PI
        System.out.println("PI:" + Math.PI);
        // public static final double E
        System.out.println("E:" + Math.E);
        System.out.println("--------------");

        // public static int abs(int a):绝对值
        System.out.println("abs:" + Math.abs(10));
        System.out.println("abs:" + Math.abs(-10));
        System.out.println("--------------");

        // public static double ceil(double a):向上取整
        System.out.println("ceil:" + Math.ceil(12.34));
        System.out.println("ceil:" + Math.ceil(12.56));
        System.out.println("--------------");

        // public static double floor(double a):向下取整
        System.out.println("floor:" + Math.floor(12.34));
        System.out.println("floor:" + Math.floor(12.56));
        System.out.println("--------------");

        // public static int max(int a,int b):最大值
        System.out.println("max:" + Math.max(12, 23));
        // 需求:我要获取三个数据中的最大值
        // 方法的嵌套调用
        System.out.println("max:" + Math.max(Math.max(12, 23), 18));
        // 需求:我要获取四个数据中的最大值
        System.out.println("max:"
                + Math.max(Math.max(12, 78), Math.max(34, 56)));
        System.out.println("--------------");

        // public static double pow(double a,double b):a的b次幂
        System.out.println("pow:" + Math.pow(2, 3));
        System.out.println("--------------");

        // public static double random():随机数 [0.0,1.0)
        System.out.println("random:" + Math.random());
        // 获取一个1-100之间的随机数
        System.out.println("random:" + ((int) (Math.random() * 100) + 1));
        System.out.println("--------------");

        // public static int round(float a) 四舍五入(参数为double的自学)
        System.out.println("round:" + Math.round(12.34f));
        System.out.println("round:" + Math.round(12.56f));
        System.out.println("--------------");

        //public static double sqrt(double a):正平方根
        System.out.println("sqrt:"+Math.sqrt(4));
    }
}

执行

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
PI:3.141592653589793
E:2.718281828459045
--------------
abs:10
abs:10
--------------
ceil:13.0
ceil:13.0
--------------
floor:12.0
floor:12.0
--------------
max:23
max:23
max:78
--------------
pow:8.0
--------------
random:0.2853933756428044
random:66
--------------
round:12
round:13
--------------
sqrt:2.0

面试题:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package cn.itcast_02;

import java.util.Scanner;

/*
 * 需求:请设计一个方法,可以实现获取任意范围内的随机数。
 * 
 * 分析:
 *      A:键盘录入两个数据。
 *          int strat;
 *          int end;
 *      B:想办法获取在start到end之间的随机数
 *          我写一个功能实现这个效果,得到一个随机数。(int)
 *      C:输出这个随机数
 */
public class MathDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入开始数:");
        int start = sc.nextInt();
        System.out.println("请输入结束数:");
        int end = sc.nextInt();

        for (int x = 0; x < 100; x++) {
            // 调用功能
            int num = getRandom(start, end);
            // 输出结果
            System.out.println(num);
        }
    }

    /*
     * 写一个功能 两个明确: 返回值类型:int 参数列表:int start,int end
     */
    public static int getRandom(int start, int end) {
        // 回想我们讲过的1-100之间的随机数
        // int number = (int) (Math.random() * 100) + 1;
        // int number = (int) (Math.random() * end) + start;
        // 发现有问题了,怎么办呢?
        int number = (int) (Math.random() * (end - start + 1)) + start;
        return number;
    }
}

**Random**类概述及其构造方法

  • Random类概述

    • 此类用于产生随机数

    • 如果用相同的种子创建两个 Random 实例,则对每个实例进行相同的方法调用序列,它们将生成并返回相同的数字序列。

  • 构造方法

    • public Random()

    • public Random(long seed)

Random类成员方法

  • public int nextInt()

  • public int nextInt(int n)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package cn.itcast_01;

import java.util.Random;

/*
 * Random:产生随机数的类
 * 
 * 构造方法:
 *      public Random():没有给种子,用的是默认种子,是当前时间的毫秒值
 *      public Random(long seed):给出指定的种子
 *
 *      给定种子后,每次得到的随机数是相同的。
 *
 * 成员方法:
 *      public int nextInt():返回的是int范围内的随机数
 *      public int nextInt(int n):返回的是[0,n)范围的内随机数
 */
public class RandomDemo {
    public static void main(String[] args) {
        // 创建对象
        // Random r = new Random();
        Random r = new Random(1111);

        for (int x = 0; x < 10; x++) {
            // int num = r.nextInt();
            int num = r.nextInt(100) + 1;
            System.out.println(num);
        }
    }
}

**System**类概述及其成员方法

  • System类概述

    • System 类包含一些有用的类字段和方法。它不能被实例化。

  • 成员方法

    • public static void gc()

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package cn.itcast_01;

/*
 * System类包含一些有用的类字段和方法。它不能被实例化。 
 * 
 * 方法:
 *      public static void gc():运行垃圾回收器。 
 *      public static void exit(int status)
 *      public static long currentTimeMillis()
 *      public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)
 */
public class SystemDemo {
    public static void main(String[] args) {
        Person p = new Person("赵雅芝", 60);
        System.out.println(p);

        p = null; // 让p不再指定堆内存
        System.gc();
/*      public static void gc()运行垃圾回收器。 
        调用 gc 方法暗示着 Java 虚拟机做了一些努力来回收未用对象,以便能够快速地重用这些对象当前占用的内存。当控制权从方法调用中返回时,虚拟机已经尽最大努力从所有丢弃的对象中回收了空间。 

        调用 System.gc() 实际上等效于调用: 

         Runtime.getRuntime().gc()*/

    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package cn.itcast_01;

public class Person {
    private String name;
    private int age;

    public Person() {
        super();
    }

    public Person(String name, int age) {
        super();
        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 "Person [name=" + name + ", age=" + age + "]";
    }

    @Override
    protected void finalize() throws Throwable {
        System.out.println("当前的对象被回收了" + this);
        super.finalize();
    }

}

• public static void exit(int status)

• public static long currentTimeMillis()

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package cn.itcast_02;

/*
 * System类包含一些有用的类字段和方法。它不能被实例化。 
 * 
 * 方法:
 *      public static void gc():运行垃圾回收器。 
 *      public static void exit(int status):终止当前正在运行的 Java 虚拟机。参数用作状态码;根据惯例,非 0 的状态码表示异常终止。 
 *      public static long currentTimeMillis():返回以毫秒为单位的当前时间
 *      public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)
 */
public class SystemDemo {
    public static void main(String[] args) {
        // System.out.println("我们喜欢林青霞(东方不败)");
        // System.exit(0);
        // System.out.println("我们也喜欢赵雅芝(白娘子)");

        // System.out.println(System.currentTimeMillis());

        // 单独得到这样的实际目前对我们来说意义不大
        // 那么,它到底有什么作用呢?
        // 要求:请大家给我统计这段程序的运行时间
        long start = System.currentTimeMillis();
        for (int x = 0; x < 100000; x++) {
            System.out.println("hello" + x);
        }
        long end = System.currentTimeMillis();
        System.out.println("共耗时:" + (end - start) + "毫秒");
    }
}

• public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package cn.itcast_03;

import java.util.Arrays;

/*
 * System类包含一些有用的类字段和方法。它不能被实例化。 
 * 
 * 方法:
 *      public static void gc():运行垃圾回收器。 
 *      public static void exit(int status):终止当前正在运行的 Java 虚拟机。参数用作状态码;根据惯例,非 0 的状态码表示异常终止。 
 *      public static long currentTimeMillis():返回以毫秒为单位的当前时间
 *      public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)
 *              从指定源数组中复制一个数组,复制从指定的位置开始,到目标数组的指定位置结束。
 */
public class SystemDemo {
    public static void main(String[] args) {
        // 定义数组
        int[] arr = { 11, 22, 33, 44, 55 };
        int[] arr2 = { 6, 7, 8, 9, 10 };

        // 请大家看这个代码的意思
        System.arraycopy(arr, 1, arr2, 2, 2); //从arr索引为1的位置取字符替代arr2中从索引为2开始的位置2个字符

        System.out.println(Arrays.toString(arr));
        System.out.println(Arrays.toString(arr2));
    }
}

执行:

1
2
[11, 22, 33, 44, 55]
[6, 7, 22, 33, 10]

BigInteger类概述及其构造方法

  • BigInteger类概述

    • 可以让超过Integer范围内的数据进行运算

  • 构造方法

    • public BigInteger(String val)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package cn.itcast_01;

import java.math.BigInteger;

/*
 * BigInteger:可以让超过Integer范围内的数据进行运算
 * 
 * 构造方法:
 * BigInteger(String val) 
 */
public class BigIntegerDemo {
    public static void main(String[] args) {
        // 这几个测试,是为了简单超过int范围内,Integer就不能再表示,所以就更谈不上计算了。
        // Integer i = new Integer(100);
        // System.out.println(i);
        // // System.out.println(Integer.MAX_VALUE);
        // Integer ii = new Integer("2147483647");
        // System.out.println(ii);
        // // NumberFormatException
        // Integer iii = new Integer("2147483648");
        // System.out.println(iii);

        // 通过大整数来创建对象
        BigInteger bi = new BigInteger("2147483648");
        System.out.println("bi:" + bi);
    }
}
1
bi:2147483648

BigInteger类成员方法

  • public BigInteger add(BigInteger val)

  • public BigInteger subtract(BigInteger val)

  • public BigInteger multiply(BigInteger val)

  • public BigInteger divide(BigInteger val)

  • public BigInteger[] divideAndRemainder(BigInteger val)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package cn.itcast_02;

import java.math.BigInteger;

/*
 * public BigInteger add(BigInteger val):加
 * public BigInteger subtract(BigInteger val):减
 * public BigInteger multiply(BigInteger val):乘
 * public BigInteger divide(BigInteger val):除
 * public BigInteger[] divideAndRemainder(BigInteger val):返回商和余数的数组
 */
public class BigIntegerDemo {
    public static void main(String[] args) {
        BigInteger bi1 = new BigInteger("100");
        BigInteger bi2 = new BigInteger("50");

        // public BigInteger add(BigInteger val):加
        System.out.println("add:" + bi1.add(bi2));
        // public BigInteger subtract(BigInteger val):加
        System.out.println("subtract:" + bi1.subtract(bi2));
        // public BigInteger multiply(BigInteger val):加
        System.out.println("multiply:" + bi1.multiply(bi2));
        // public BigInteger divide(BigInteger val):加
        System.out.println("divide:" + bi1.divide(bi2));

        // public BigInteger[] divideAndRemainder(BigInteger val):返回商和余数的数组
        BigInteger[] bis = bi1.divideAndRemainder(bi2);
        System.out.println("商:" + bis[0]);
        System.out.println("余数:" + bis[1]);
    }
}

执行:

1
2
3
4
5
6
add:150
subtract:50
multiply:5000
divide:2
2
余数0

BigDecimal类概述及其构造方法

  • 由于在运算的时候,float类型和double很容易丢失精度,演示案例。所以,为了能精确的表示、计算浮点数,Java提供了BigDecimal
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
package cn.itcast_01;

/*
 * 看程序写结果:结果和我们想的有一点点不一样,这是因为float类型的数据存储和整数不一样导致的。它们大部分的时候,都是带有有效数字位。
 * 
 * 由于在运算的时候,float类型和double很容易丢失精度,演示案例。所以,为了能精确的表示、计算浮点数,Java提供了BigDecimal
 * 
 * BigDecimal类:不可变的、任意精度的有符号十进制数,可以解决数据丢失问题。
 */
public class BigDecimalDemo {
    public static void main(String[] args) {
        System.out.println(0.09 + 0.01);
        System.out.println(1.0 - 0.32);
        System.out.println(1.015 * 100);
        System.out.println(1.301 / 100);

        System.out.println(1.0 - 0.12);
    }
}

执行:

1
2
3
4
5
0.09999999999999999
0.6799999999999999
101.49999999999999
0.013009999999999999
0.88
  • BigDecimal类概述

    • 不可变的、任意精度的有符号十进制数。

  • 构造方法

    • public BigDecimal(String val)

BigDecimal类成员方法

  • public BigDecimal add(BigDecimal augend)

  • public BigDecimal subtract(BigDecimal subtrahend)

  • public BigDecimal multiply(BigDecimal multiplicand)

  • public BigDecimal divide(BigDecimal divisor)

  • public BigDecimal divide(BigDecimal divisor,int scale, int roundingMode)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package cn.itcast_02;

import java.math.BigDecimal;

/*
 * 构造方法:
 *      public BigDecimal(String val)
 * 
 * public BigDecimal add(BigDecimal augend)
 * public BigDecimal subtract(BigDecimal subtrahend)
 * public BigDecimal multiply(BigDecimal multiplicand)
 * public BigDecimal divide(BigDecimal divisor)
 * public BigDecimal divide(BigDecimal divisor,int scale,int roundingMode):商,几位小数,如何舍取
 */
public class BigDecimalDemo {
    public static void main(String[] args) {
        // System.out.println(0.09 + 0.01);
        // System.out.println(1.0 - 0.32);
        // System.out.println(1.015 * 100);
        // System.out.println(1.301 / 100);

        BigDecimal bd1 = new BigDecimal("0.09");
        BigDecimal bd2 = new BigDecimal("0.01");
        System.out.println("add:" + bd1.add(bd2));
        System.out.println("-------------------");

        BigDecimal bd3 = new BigDecimal("1.0");
        BigDecimal bd4 = new BigDecimal("0.32");
        System.out.println("subtract:" + bd3.subtract(bd4));
        System.out.println("-------------------");

        BigDecimal bd5 = new BigDecimal("1.015");
        BigDecimal bd6 = new BigDecimal("100");
        System.out.println("multiply:" + bd5.multiply(bd6));
        System.out.println("-------------------");

        BigDecimal bd7 = new BigDecimal("1.301");
        BigDecimal bd8 = new BigDecimal("100");
        System.out.println("divide:" + bd7.divide(bd8));
        System.out.println("divide:"
                + bd7.divide(bd8, 3, BigDecimal.ROUND_HALF_UP));
        System.out.println("divide:"
                + bd7.divide(bd8, 8, BigDecimal.ROUND_HALF_UP));
    }
}

执行

1
2
3
4
5
6
7
8
9
add:0.10
-------------------
subtract:0.68
-------------------
multiply:101.500
-------------------
divide:0.01301
divide:0.013
divide:0.01301000

**Date**类概述及其方法

  • Date类概述

    • 类 Date 表示特定的瞬间,精确到毫秒。

  • 构造方法

    • public Date()

    • public Date(long date)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package cn.itcast_01;

import java.util.Date;

/*
 * Date:表示特定的瞬间,精确到毫秒。 
 * 
 * 构造方法:
 *      Date():根据当前的默认毫秒值创建日期对象
 *      Date(long date):根据给定的毫秒值创建日期对象
 */
public class DateDemo {
    public static void main(String[] args) {
        // 创建对象
        Date d = new Date();
        System.out.println("d:" + d);

        // 创建对象
        // long time = System.currentTimeMillis();
        long time = 1000 * 60 * 60; // 1小时
        Date d2 = new Date(time);  
        System.out.println("d2:" + d2);
    }
}

执行:

1
2
d:Mon Jun 10 17:18:29 CST 2019
d2:Thu Jan 01 09:00:00 CST 1970
  • 成员方法

    • public long getTime()

    • public void setTime(long time)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package cn.itcast_02;

import java.util.Date;

/*
 * public long getTime():获取时间,以毫秒为单位
 * public void setTime(long time):设置时间
 * 
 * 从Date得到一个毫秒值
 *      getTime()
 * 把一个毫秒值转换为Date
 *      构造方法
 *      setTime(long time)
 */
public class DateDemo {
    public static void main(String[] args) {
        // 创建对象
        Date d = new Date();

        // 获取时间
        long time = d.getTime();
        System.out.println(time);
        // System.out.println(System.currentTimeMillis());

        System.out.println("d:" + d);
        // 设置时间
        d.setTime(1000);
        System.out.println("d:" + d);
    }
}

执行:

1
2
3
1560158711041
d:Mon Jun 10 17:25:11 CST 2019
d:Thu Jan 01 08:00:01 CST 1970

DateFormat类概述及其方法

  • DateFormat类概述

    • DateFormat 是日期/时间格式化子类的抽象类,它以与语言无关的方式格式化并解析日期或时间。

    • 是抽象类,所以使用其子类SimpleDateFormat

  • SimpleDateFormat构造方法

    • public SimpleDateFormat()

    • public SimpleDateFormat(String pattern)

  • 成员方法

    • public final String format(Date date)

    • public Date parse(String source)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package cn.itcast_03;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
 * Date  --  String(格式化)
 *      public final String format(Date date)
 * 
 * String -- Date(解析)
 *      public Date parse(String source)
 * 
 * DateForamt:可以进行日期和字符串的格式化和解析,但是由于是抽象类,所以使用具体子类SimpleDateFormat。
 * 
 * SimpleDateFormat的构造方法:
 *      SimpleDateFormat():默认模式
 *      SimpleDateFormat(String pattern):给定的模式
 *          这个模式字符串该如何写呢?
 *          通过查看API,我们就找到了对应的模式
 *          年 y
 *          月 M 
 *          日 d
 *          时 H
 *          分 m
 *          秒 s
 * 
 *          2014年12月12日 12:12:12
 */
public class DateFormatDemo {
    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");
        // public final String format(Date date)
        String s = sdf.format(d);
        System.out.println(s);


        //String -- Date
        String str = "2008-08-08 12:12:12";
        //在把一个字符串解析为日期的时候,请注意格式必须和给定的字符串格式匹配
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dd = sdf2.parse(str);
        System.out.println(dd);
    }
}

执行:

1
2
2019年06月10日 18:35:59
Fri Aug 08 12:12:12 CST 2008

Date类及DateFormat类练习

  • 制作一个工具类。DateUtil
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package cn.itcast_04;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 这是日期和字符串相互转换的工具类
 * 
 * @author 风清扬
 */
public class DateUtil {
    private DateUtil() {
    }

    /**
     * 这个方法的作用就是把日期转成一个字符串
     * 
     * @param d
     *            被转换的日期对象
     * @param format
     *            传递过来的要被转换的格式
     * @return 格式化后的字符串
     */
    public static String dateToString(Date d, String format) {
        // SimpleDateFormat sdf = new SimpleDateFormat(format);
        // return sdf.format(d);
        return new SimpleDateFormat(format).format(d);
    }

    /**
     * 这个方法的作用就是把一个字符串解析成一个日期对象
     * 
     * @param s
     *            被解析的字符串
     * @param format
     *            传递过来的要被转换的格式
     * @return 解析后的日期对象
     * @throws ParseException
     */
    public static Date stringToDate(String s, String format)
            throws ParseException {
        return new SimpleDateFormat(format).parse(s);
    }
}

测试:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package cn.itcast_04;

import java.text.ParseException;
import java.util.Date;

/*
 * 工具类的测试
 */
public class DateUtilDemo {
    public static void main(String[] args) throws ParseException {
        Date d = new Date();
        // yyyy-MM-dd HH:mm:ss
        String s = DateUtil.dateToString(d, "yyyy年MM月dd日 HH:mm:ss");
        System.out.println(s);

        String s2 = DateUtil.dateToString(d, "yyyy年MM月dd日");
        System.out.println(s2);

        String s3 = DateUtil.dateToString(d, "HH:mm:ss");
        System.out.println(s3);

        String str = "2014-10-14";
        Date dd = DateUtil.stringToDate(str, "yyyy-MM-dd");
        System.out.println(dd);
    }
}

执行:

1
2
3
4
2019年06月10日 18:52:46
2019年06月10日
18:52:46
Tue Oct 14 00:00:00 CST 2014
  • 算一下你来到这个世界多少天?
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package cn.itcast_05;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

/*
 * 算一下你来到这个世界多少天?
 * 
 * 分析:
 *      A:键盘录入你的出生的年月日
 *      B:把该字符串转换为一个日期
 *      C:通过该日期得到一个毫秒值
 *      D:获取当前时间的毫秒值
 *      E:用D-C得到一个毫秒值
 *      F:把E的毫秒值转换为年
 *          /1000/60/60/24
 */
public class MyYearOldDemo {
    public static void main(String[] args) throws ParseException {
        // 键盘录入你的出生的年月日
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入你的出生年月日:");
        String line = sc.nextLine();

        // 把该字符串转换为一个日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date d = sdf.parse(line);

        // 通过该日期得到一个毫秒值
        long myTime = d.getTime();

        // 获取当前时间的毫秒值
        long nowTime = System.currentTimeMillis();

        // 用D-C得到一个毫秒值
        long time = nowTime - myTime;

        // 把E的毫秒值转换为年
        long day = time / 1000 / 60 / 60 / 24;

        System.out.println("你来到这个世界:" + day + "天");
    }
}

执行

1
2
3
请输入你的出生年月日:
1996-01-17
你来到这个世界8545

Calendar类概述及其方法

  • Calendar类概述

    • Calendar 类是一个抽象类,它为特定瞬间与一组诸如 YEAR、MONTH、DAY_OF_MONTH、HOUR 等日历字段之间的转换提供了一些方法,并为操作日历字段(例如获得下星期的日期)提供了一些方法。

  • 成员方法

    • public static Calendar getInstance()

    • public int get(int field)

    • public void add(int field,int amount)

    • public final void set(int year,int month,int date)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package cn.itcast_01;

import java.util.Calendar;

/*
 * Calendar:它为特定瞬间与一组诸如 YEAR、MONTH、DAY_OF_MONTH、HOUR 等 日历字段之间的转换提供了一些方法,并为操作日历字段(例如获得下星期的日期)提供了一些方法。
 * 
 * public int get(int field):返回给定日历字段的值。日历类中的每个日历字段都是静态的成员变量,并且是int类型。
 */
public class CalendarDemo {
    public static void main(String[] args) {
        // 其日历字段已由当前日期和时间初始化:
        Calendar rightNow = Calendar.getInstance(); // 子类对象

        // 获取年
        int year = rightNow.get(Calendar.YEAR);
        // 获取月
        int month = rightNow.get(Calendar.MONTH);
        // 获取日
        int date = rightNow.get(Calendar.DATE);

        System.out.println(year + "年" + (month + 1) + "月" + date + "日");
    }
}

/*
 * abstract class Person { public static Person getPerson() { return new
 * Student(); } }
 * 
 * class Student extends Person {
 * 
 * }
 */
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package cn.itcast_02;

import java.util.Calendar;

/*
 * public void add(int field,int amount):根据给定的日历字段和对应的时间,来对当前的日历进行操作。
 * public final void set(int year,int month,int date):设置当前日历的年月日
 */
public class CalendarDemo {
    public static void main(String[] args) {
        // 获取当前的日历时间
        Calendar c = Calendar.getInstance();

        // 获取年
        int year = c.get(Calendar.YEAR);
        // 获取月
        int month = c.get(Calendar.MONTH);
        // 获取日
        int date = c.get(Calendar.DATE);
        System.out.println(year + "年" + (month + 1) + "月" + date + "日");

        // // 三年前的今天
        // c.add(Calendar.YEAR, -3);
        // // 获取年
        // year = c.get(Calendar.YEAR);
        // // 获取月
        // month = c.get(Calendar.MONTH);
        // // 获取日
        // date = c.get(Calendar.DATE);
        // System.out.println(year + "年" + (month + 1) + "月" + date + "日");

        // 5年后的10天前
        c.add(Calendar.YEAR, 5);
        c.add(Calendar.DATE, -10);
        // 获取年
        year = c.get(Calendar.YEAR);
        // 获取月
        month = c.get(Calendar.MONTH);
        // 获取日
        date = c.get(Calendar.DATE);
        System.out.println(year + "年" + (month + 1) + "月" + date + "日");
        System.out.println("--------------");

        c.set(2011, 11, 11);
        // 获取年
        year = c.get(Calendar.YEAR);
        // 获取月
        month = c.get(Calendar.MONTH);
        // 获取日
        date = c.get(Calendar.DATE);
        System.out.println(year + "年" + (month + 1) + "月" + date + "日");
    }
}

执行:

1
2
3
4
2019年6月10日
2024年5月31日
--------------
2011年12月11日

Calendar类练习

  • 算一下你来到这个世界多少天?

  • 获取任意一年的二月有多少天

面试题:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package cn.itcast_03;

import java.util.Calendar;
import java.util.Scanner;

/*
 * 获取任意一年的二月有多少天
 * 
 * 分析:
 *      A:键盘录入任意的年份
 *      B:设置日历对象的年月日
 *          年就是A输入的数据
 *          月是2
 *          日是1
 *      C:把时间往前推一天,就是2月的最后一天
 *      D:获取这一天输出即可
 */
public class CalendarTest {
    public static void main(String[] args) {
        // 键盘录入任意的年份
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入年份:");
        int year = sc.nextInt();

        // 设置日历对象的年月日
        Calendar c = Calendar.getInstance();
        c.set(year, 2, 1); // 其实是这一年的3月1日
        // 把时间往前推一天,就是2月的最后一天
        c.add(Calendar.DATE, -1);

        // 获取这一天输出即可
        System.out.println(c.get(Calendar.DATE));
    }
}

执行

1
2
3
请输入年份
2008
29