java入门~第十五天 基本数据类型包装类,各种常用类.以及正则表达式md

1.基本数据类型包装类

1.01基本类型包装类的概述

需求:
a:将100转换成二进制 , 八进制 , 十六进制
b:判断一个数是否在int的范围内

if(25252525>=Integer.MIN_VALUE&& 25252525<=Integer.MAX_VALUE){
    System.out.println("在int范围内");
}

1.为什么会有基本类型包装类:
为了对基本数据类型进行更多的操作,更方便的操作,java就针对每一种基本数据类型提供了对应的类类型.
2.常用操作: 常用的操作之一:用于基本数据类型与字符串之间的转换。
3.基本类型和包装类的对应
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean

public static void main(String[] args) {
    int num=100;
    String s = Integer.toBinaryString(num);
    String s1 = Integer.toOctalString(num);
    String s2 = Integer.toHexString(num);
    System.out.println(s); //1100100
    System.out.println(s1);//144
    System.out.println(s2);//64
}

1.02Integer类的概述和构造方法

1.Integer 类在对象中包装了一个基本类型 int 的值。Integer 类型的对象包含一个 int 类型的字段。此外,该类提供了多个方法,能在 int 类型和 String 类型之间互相转换,还提供了处理 int 类型时非常有用的其他一些常量和方法。

2.Integer( int value)
构造一个新分配的 Integer 对象,它表示指定的 int 值。
Integer(String s)
构造一个新分配的 Integer 对象,它表示 String 参数所指示的 int 值。

int num=100;
//把int类型的值,包装成引用类型。
Integer integer = new Integer(num);
//要的这个字符串,字面上是一个数字的字符串。
Integer integer2 = new Integer("200");
System.out.println( integer ); //100
System.out.println(integer2);//200

1.03String和int类型的相互转换

1.int – String
a:和""进行拼接
b:public static String valueOf(int i)
c:int – Integer – String
d:public static String toString(int i)
2.String – int
a:String – Integer – intValue();
b:public static int parseInt(String s)

public static void main(String[] args) {
    //String和int类型的相互转换
    //int----String
    int num=100; //"100"
    //方式1:
    String str=num+"";

    //方式2:
    String s = String.valueOf(num);

    //方式s:

    Integer integer = new Integer(num);
    String s1 = integer.toString();

    //String-----int
    String strNum="100";
    //方式1
    Integer integer1 = new Integer(strNum);
    int i = integer1.intValue();

    //方式2:
    int i1 = Integer.parseInt(strNum);


}

1.04JDK5的新特性自动装箱和拆箱

JDK5的新特性:
自动装箱:把基本类型转换为包装类类
自动拆箱:把包装类类型转换为基本类型

拆箱:

public static void main(String[] args) {
    Integer a = new Integer(100);
    Integer b = new Integer(100);
    //自动拆箱 String类型转成int直接进行加减。
    int r=a+b;
    System.out.println(r);//200
}
//手动拆箱 intValue();

Integer c = new Integer(100);
Integer d = new Integer(100);
//手动拆箱
int i = c.intValue();
int i1 = d.intValue();
System.out.println(i+i1);

装箱:

public static void main(String[] args) {
        //自动装箱
        Integer ii = 100;
        ii += 200; //自动拆箱,自动装箱。

        //Integer 重写了i1.equals(i2)方法,比较的是,他包装的这个值是否相同
        //Integer 重写了toString()方法,把他包装的这个int类型的数据,转换成字符串。

        String s = ii.toString();
        System.out.println(s+"aaa"); //"300aaa"

    
}

1.05Integer的面试题

public static void main(String[] args) {
    Integer i1 = new Integer(127);
    Integer i2 = new Integer(127);

    System.out.println(i1 == i2); //false
    //Integer 重写了i1.equals(i2)方法,比较的是,他包装的这个值是否相同
    System.out.println(i1.equals(i2)); //true
    System.out.println("-----------");

    Integer i3 = new Integer(128);
    Integer i4 = new Integer(128);
    System.out.println(i3 == i4); //false
    System.out.println(i3.equals(i4));//true
    System.out.println("-----------");

    Integer i5 = 128;
    Integer i6 = 128;
    System.out.println(i5 == i6);//  false
    System.out.println(i5.equals(i6)); //true
    System.out.println("-----------");

    Integer i7 = 127;
    Integer i8 = 127;
    System.out.println(i7 == i8);//true
    System.out.println(i7.equals(i8)); //true
}

分析:对于前两组结果的输出很简单,==比较的是地址值,equals()方法比较的是对象的内容;

​ 在自动拆箱的时候,编译器会使用Integer.valueof()来创建Integer实例,如果传入的int在IntegerCache.low(默认为-128)和IntegerCache.high(默认为127)之间,那就看之前的缓存有没有打包过相同的值,如果有直接返回,否则就创建一个。

public static void main(String[] args) {
    long num=1000L;
    Long aLong = Long.valueOf(num); //手动装箱
    Long aLong1 = new Long(num);//构造方法拆箱
    long l = aLong.longValue();
    long l1 = aLong1.longValue();

    Long aLong2 = new Long("11122242442");


    String longNum="22222224244241";
    long l2 = Long.parseLong(longNum);

    System.out.println("=========================");
    String b="true"; //true
    boolean b1 = Boolean.parseBoolean(b);

    Boolean aBoolean = new Boolean(false);

    boolean b2 = aBoolean.booleanValue();

    Boolean aTrue = Boolean.valueOf("true");
    Boolean aBoolean1 = Boolean.valueOf(false);


}

2.正则表达式

2.01正则表达式的概述和简单使用

1.正则表达式:

​ 正确规则的表达式 规则java给我们定的
​ 是指一个用来描述或者匹配一系列符合某个句法规则的字符串的单个字符。其实就是一种规则。有自己特殊的应用。

2.案例演示
需求:校验qq号码.
1:要求必须是5-15位数字
2:0不能开头

a:非正则表达式实现:

public class MyTest {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入的你的QQ号");
        String qqNumber = sc.nextLine();
        //调用校验的方法
        // boolean flag = checkQQNumber(qqNumber);
        boolean flag = checkQQNumber2(qqNumber);
        if (flag) {
            System.out.println("QQ号规则正确");
        } else {
            System.out.println("QQ号规则错误");
        }
    }
    

    }
    private static boolean checkQQNumber(String qqNumber) {
        // 1:要求必须是5 - 15 位数字
        //  2:0 不能开头
        //定义一个标记
        boolean flag = false;
        if (qqNumber.length() >= 5 && qqNumber.length() <= 15 && !qqNumber.startsWith("0")) {
            //判断每一位是数字字符
            for (int i = 0; i < qqNumber.length(); i++) {
                char ch = qqNumber.charAt(i);
                if (!Character.isDigit(ch)) {
                    flag = false;
                    break;
                } else {
                    flag = true;
                }
            }
        }
        return flag;
    }
}

b:正则表达式实现 :

private static boolean checkQQNumber2(String qqNumber) {
    //定义正则表达式
    String regx = "[1-9][0-9]{4,14}";
    boolean b = qqNumber.matches(regx);
    return b;

}

2.手机号:

​ 校验手机号的规则 :手机号 11 位, 第一位是 1 第二位 3 5 7 8 ,其余位随意数字 手机号每一位都是数字。

public class MyTest2 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入的你的手机号");
        String phoneNumber = sc.nextLine();
        boolean flag = checkphoneNumber(phoneNumber);
        if (flag) {
            System.out.println("手机号规则正确");
        } else {
            System.out.println("手机号规则错误");
        }
    }

    private static boolean checkphoneNumber(String phoneNumber) {
        boolean flag = false;
        if (phoneNumber.length() == 11 && phoneNumber.startsWith("13") || phoneNumber.startsWith("15") || phoneNumber.startsWith("17") || phoneNumber.startsWith("18")) {
            for (int i = 2; i < phoneNumber.length(); i++) {
                char ch = phoneNumber.charAt(i);
                if (!Character.isDigit(ch)) {
                    flag = false;
                    break;
                } else {
                    flag = true;
                }
            }

        }
        return flag;
    }
}

正则表达式:

String phoneRegx="[1][3,5,7,8][0-9]{9}";
//matches(phoneRegx); 判断这个字符串,是否符合传入的这个正则表达式。
boolean b = "13259856542".matches(phoneRegx);
System.out.println(b);

3.邮箱:

  public static void main(String[] args) {
       /* static boolean isLetterOrDigit ( char ch)
        确定指定字符是否为字母或数字*/
        // System.out.println(Character.isLetterOrDigit('@'));
      /*  static boolean isDefined ( char ch)
        确定字符是否被定义为 Unicode 中的字符。*/
        //System.out.println(Character.isDefined('_'));

        Scanner sc = new Scanner(System.in);
        System.out.println("请输入的你网易邮箱号");
        String email = sc.nextLine();
        boolean flag = checkEmail(email);
        if (flag) {
            System.out.println("邮箱规则正确");
        } else {
            System.out.println("邮箱规则错误");
        }
    }

    private static boolean checkEmail(String emailName) {
        boolean flag = false;
        if (emailName.endsWith("@163.com") && emailName.length() >= 14 && emailName.length() <= 26 && Character.isLetter(emailName.charAt(0))) {
            String s = emailName.substring(0, emailName.lastIndexOf("@"));
            System.out.println(s);
            for (int i = 1; i < s.length(); i++) {
                char ch = s.charAt(i);
                if (!(Character.isLetterOrDigit(ch) || ch == '_')) {
                    flag = false;
                    break;
                } else {
                    flag = true;
                }
            }
        }
        return flag;
    }
}

正则表达式:

String emailRegx="[a-zA-Z]\\w{5,17}@163\\.com";

2.02正则表达式的组成规则

1.字符类

//定义正则表达式:
String regx = “a”;
regx = “[a,b,c]”; //是我列举的某一个
regx = “[a-z]”;
regx = “[A,B,C,D]”;
regx = “[A-Z]”;
regx = “[a-zA-Z]”;
regx = “[0,1,2,3]”;
regx = “[0-9]”;
regx = “[a-zA-Z0-9]”;
regx = “[^ 0-9]”; //^不是列表中的某一个
regx = “.”;//配置单个任意字符。
regx = “\.”; // \ 转义字符 点.
regx = “|”; // | 或者
regx = “\|”;
regx = “\d”; // 跟 [0-9] 这个的意思一样 \D 非数字: [^0 - 9]
regx = “\w”; // 跟 [a-zA-Z_0-9] 这个意思一样 \W 非单词字符:[^\w]
regx = " ";
regx = “\s”; //空格 \S 非空白字符:[^\s]
regx = “abc$”; //以abc结尾
regx = “^abc”; // 以abc开头
regx = “[0-9]+”; //0-9 + 可以出现一个或多个
regx = “[a-z]*”; //a-z * 0个或多个 1个也算多个 空串算0个
regx = “[A-Z]?”; // ? 一个或 0个
regx = “\w+”;
regx = “[a-zA-Z0-9_]+”;
regx = “[a-z]{6}”; //正好几个
regx = “[a-zA-Z]{6,}”; //至少6个
regx = “[a-zA-Z]{6,16}”; //大于等于6 小于等于16

\b 单词边界
就是不是单词字符的地方。

2.03正则表达式的判断功能

正则表达式的判断功能:
String类的功能:public boolean matches(String regex)

2.04正则表达式的分割功能

正则表达式的分割功能 split()方法
String类的功能:public String[] split(String regex)

public class MyTest {
    public static void main(String[] args) {
        String names="张三=李四=王五";
        String s = names.substring(0, names.indexOf("="));
        System.out.println(s);
        String s1 = names.substring(names.indexOf("=")+1, names.lastIndexOf("="));
        System.out.println(s1);
        String s2 = names.substring(names.lastIndexOf("=")+1);
        System.out.println(s2);
        System.out.println("===================================");
        //根据正则来切割这个字符串,返回的是一个字符串数组。
        String[] strings = names.split("=");
        System.out.println(strings[0]);
        System.out.println(strings[1]);
        System.out.println(strings[2]);
        System.out.println("================================");

        String names2 = "张三assdfa=12542242assadfafasdf2411李四asdfdadsf25244=asdfasdf25411王五"; //
        String[] arr = names2.split("[a-z=0-9]+");
        System.out.println(arr[0]);
        System.out.println(arr[1]);
        System.out.println(arr[2]);

    }
}

例题:把给定字符串中的数字排序

需求:我有如下一个字符串:”91 27 46 38 50”,请写代码实现最终输出结果是:”27 38 46 50 91”

  • 分析:
  • a: 定义目标字符串"91 27 46 38 50"
  • b: 对这个字符串进行切割,得到的就是一个字符串数组
  • c: 把b中的字符串数组转换成int类型的数组
  • (1): 定义一个int类型的数组,数组的长度就是字符串数组长度
  • (2): 遍历字符串数组,获取每一个元素.将其转换成int类型的数据
  • (3): 把int类型的数据添加到int类型的数组的指定位置
  • d: 排序
  • e: 创建一个StringBuilder对象,用来记录拼接的结果
  • f: 遍历int类型的数组, 将其每一个元素添加到StringBuilder对象中
  • g: 就是把StringBuilder转换成String
  • h: 输出
public class MyTest2 {
    public static void main(String[] args) {
        String str = "91   27  46    38       50 5 300 1 100 3 200";
        //"1 3 5 27" 得到一个排好序的字符串
        String[] strings = str.split("\\s+");
        //你排序的是字符串数组,按照元素的字典顺序来排序的。
        //Arrays.sort(strings);
        //System.out.println(Arrays.toString(strings));
        int[] arr = new int[strings.length];

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

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

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            sb.append(arr[i]).append(" ");
        }

        String s = sb.toString().trim();
        System.out.println(s);

    }
}

2.05正则表达式的替换功能

String类的功能:public String replaceAll(String regex,String replacement)

"[ ^ \u4e00-\u9fa5 ] "判断字符串中是否包含中文

2.06Pattern和Matcher的概述

正则的获取功能需要使用的类:

​ Pattern和Matcher

模式和匹配器的典型调用顺序
通过JDK提供的API,查看Pattern类的说明

典型的调用顺序是
Pattern p = Pattern.compile(“a*b”);
Matcher m = p.matcher(“aaaaab”);
boolean b = m.matches();

public static void main(String[] args) {
    //匹配器Matche   模式器Pattern
    //把一个正则表达式封装到模式器里面
    Pattern p = Pattern.compile("a*b");
    //调用模式器中的matcher("aaaaab");方法,传入一个待匹配的数据,返回一个匹配器
    Matcher m = p.matcher("aaaaab");
    //调用匹配器中的匹配的方法,看数据是否匹配正则
    boolean b = m.matches();
    System.out.println(b);

    //如果你的需求只是看一个数据符不符合一个正则,你只需要调用,String类中的matches("a*b")
    System.out.println("aaaaab".matches("a*b"));//"a*b"正则表达式


    //之所以Java给我提供了  匹配器Matche   模式器Pattern 这两个类,是因为,这两个类中有更丰富的方法供我们使用

}

2.07正则表达式的获取功能

正则表达式的获取功能
Pattern和Matcher的结合使用,使用的是boolean find()方法 和String group()方法 注意一定要先使用find()方法先找到 才能用group()方法获取出来

public static void main(String[] args) {
    //获取下面字符串中 是三个字母组成的单词。
   // da jia ting wo shuo, jin tian yao xia yu, bu shang wan zi xi, gao xing bu?

    String str="da jia ting wo shuo, jin tian yao xia yu, bu shang wan zi xi, gao xing bu?";
    String[] s = str.replace(",", "").replace("?", "").split(" ");
    for (int i = 0; i < s.length; i++) {
        if(s[i].length()==3){
            System.out.println(s[i]);
        }
    }
}
 String regx="\\b[a-z]{3}\\b";

  Pattern pattern = Pattern.compile(regx);
   Matcher matcher = pattern.matcher(str);

/*   boolean b = matcher.find();
   System.out.println(b);
   if(b){
       String s = matcher.group();
       System.out.println(s);
   }*/

   while (matcher.find()) {
       String s = matcher.group();
       System.out.println(s);
   }

爬虫例子:

public static void main(String[] args) {
    String str = "div class=\"ntes-nav-select-pop\">\n" +
            "            <ul class=\"ntes-nav-select-list clearfix\">\n" +
            "              <li>\n" +
            "                <a href=\"http://m.163.com/newsapp/#f=topnav\">\n" +
            "                  <span>\n" +
            "                    <em class=\"ntes-nav-app-newsapp\">网易新闻</em>\n" +
            "                  </span>\n" +
            "                </a>\n" +
            "              </li>\n" +
            "              <li>\n" +
            "                <a href=\"http://open.163.com/#f=topnav\">\n" +
            "                  <span>\n" +
            "                    <em class=\"ntes-nav-app-open\">网易公开课</em>\n" +
            "                  </span>\n" +
            "                </a>\n" +
            "              </li>\n" +
            "              <li>\n" +
            "                <a href=\"https://hongcai.163.com/?from=pcsy-button\">\n" +
            "                  <span>\n" +
            "                    <em class=\"ntes-nav-app-hongcai\">网易红彩</em>\n" +
            "                  </span>\n" +
            "                </a>\n" +
            "              </li>              \n" +
            "              <li>\n" +
            "                <a href=\"https://gulu.163.com\">\n" +
            "                  <span>\n" +
            "                    <em class=\"ntes-nav-app-gulu-video\">网易新闻视频版</em>\n" +
            "                  </span>\n" +
            "                </a>\n" +
            "              </li>\n" +
            "              <li>\n" +
            "                <a href=\"http://u.163.com/aosoutbdbd8\">\n" +
            "                  <span>\n" +
            "                    <em class=\"ntes-nav-app-yanxuan\">网易严选</em>\n" +
            "                  </span>\n" +
            "                </a>\n" +
            "              </li>\n" +
            "              <li>\n" +
            "                <a href=\"http://mail.163.com/client/dl.html?from=mail46\">\n" +
            "                  <span>\n" +
            "                    <em class=\"ntes-nav-app-mail\">邮箱大师</em>\n" +
            "                  </span>\n" +
            "                </a>\n" +
            "              </li>\n" +
            "              <li class=\"last\">\n" +
            "                <a href=\"http://study.163.com/client/download.htm?from=163app&utm_source=163.com&utm_medium=web_app&utm_campaign=business\">\n" +
            "                  <span>\n" +
            "                    <em class=\"ntes-nav-app-study\">网易云课堂</em>\n" +
            "                  </span>\n" +
            "                </a>\n" +
            "              </li>\n" +
            "            </ul>\n" +
            "          </div>\n" +
            "        </div>";

    String httpregx = "http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+";

    Pattern pattern = Pattern.compile(httpregx);   //
    Matcher matcher = pattern.matcher(str);

    while (matcher.find()) {
        String s = matcher.group();
        System.out.println(s);
    }
}

3.Math类

3.01Math的概述和方法使用

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

2.成员变量
public static final double E : 自然底数
public static final double PI: 圆周率
3.成员方法
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) 获取最大值
public static int min(int a, int b) 获取最小值
public static double pow(double a,double b) 获取a的b次幂
public static double random() 获取随机数 返回带正号的 double 值,该值大于等于 0.0 且小于 1.0。
public static int round(float a) 四舍五入
public static double sqrt(double a) 获取正平方根

public static void main(String[] args) {
    System.out.println(Math.PI);
    System.out.println(Math.E);

    System.out.println(Math.abs(-1));
    System.out.println(Math.ceil(3.1));
    System.out.println(Math.floor(3.1));
    System.out.println(Math.random());
    System.out.println(Math.max(3.1, 36.2));
    System.out.println(Math.max(Math.max(3.1, 36.2),36));
    System.out.println(Math.min(3.3, 68));

    System.out.println(Math.pow(3, 3));
    System.out.println(Math.sqrt(4));
    System.out.println(Math.round(3.5));

    System.out.println(Math.pow(8, 1/3.0));

}

4.Random类

1.Random类的概述
此类用于产生随机数,如果用相同的种子创建两个 Random 实例,
则对每个实例进行相同的方法调用序列**,它们将生成并返回相同的数字序列**。
2.构造方法
public Random() 没有给定种子,使用的是默认的(当前系统的毫秒值)
public Random(long seed) 给定一个long类型的种子,给定以后每一次生成的随机数是相同的
3.成员方法
public int nextInt() //没有参数 表示的随机数范围 在int类型的范围
public int nextInt(int n) //可以指定一个随机数范围 ,就是小于n的随机数
void nextBytes(byte[] bytes) //生成随机字节并将其置于用户提供的空的 byte 数组中。

​ public double next double () //生0.0-1.0随机数

​ public double nextBoolean() //生成布尔类型

public static void main(String[] args) {
    Random random = new Random();
    for (int i = 0; i < 100; i++) {
        //生成的范围是int的范围
        int num= random.nextInt();
        //指定范围来生成随机数
        int num = random.nextInt(10);
        System.out.println(num);
        double v = random.nextDouble();
        System.out.println(v);
        boolean b = random.nextBoolean();
        System.out.println(b);
    }
    byte[] bytes = new byte[10];
    random.nextBytes(bytes);

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

5.System类

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

2.成员方法
public static void gc()//调用垃圾回收器

public static void main(String[] args) {
    //运行垃圾回收器,回收垃圾。
    System.gc();
   // Runtime.getRuntime().gc();
  //System.gc();和Runtime.getRuntime().gc();都会强制触发垃圾收集,System.gc();掉起来更方便,但会给应用带来不必要的性能问题,还可以通过参数XX:DisableExplicitGC.禁止显示调用gc.
  //Runtime.getRuntime().gc();建议用于JVM花费精力回收不再使用的对象。
    //ctrl+alt+空格
    String property = System.getProperty("java.version"); //版本
    String property1 = System.getProperty("java.class.path");//装的位置
    System.out.println(property);
    System.out.println(property1);

​ public static void exit(int status)//退出java虚拟机 0 为正常退出 非0为 异常退出

public static void main(String[] args) {
    //exit(0); 退出虚拟机
    System.out.println("abcb");
    System.out.println("abcb");
    //0 正常退出 非0 强制退出
    System.exit(0);
    System.out.println("abcb");//后面的这个就不会运行了
}

public static long currentTimeMillis()//获取当前时间的毫秒值

指的是获取从 1970 年 1 月 1 日 00:00:00 到现在 所间隔的毫秒值

System.err.println("错误信息");
public static void main(String[] args) {
    //获取当前系统时间的毫秒值
    //1s=1000ms
    //获取从 1970 01-01 00:00:00 到现在的间隔的 毫秒值
    long timeMillis = System.currentTimeMillis();

    System.out.println(timeMillis);

    //测试循环的耗时
    for (int i = 0; i < 500000; i++) {
        System.out.println(i);
    }

    long timeMillis2 = System.currentTimeMillis();

    System.out.println("耗时"+(timeMillis2-timeMillis)+"毫秒");

}

6.BigDecimal类的概述和方法使用

1.BigDecimal的概述
由于在运算的时候,float类型和double很容易丢失精度,演示案例。
所以,为了能精确的表示、计算浮点数,Java提供了BigDecimal

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

2.构造方法
public BigDecimal(String val)
3.成员方法
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)//scale 小数点后面保留几位
// roundingMode 取舍模式 比如四舍五入:

1ROUND_UP舍入远离零的舍入模式。在丢弃非零部分之前始终增加数字(始终对非零舍弃部分前面的数字加1)。注意,此舍入模式始终不会减少计算值的大小。

2ROUND_DOWN接近零的舍入模式。在丢弃某部分之前始终不增加数字(从不对舍弃部分前面的数字加1,即截短)。注意,此舍入模式始终不会增加计算值的大小。

3ROUND_CEILING接近正无穷大的舍入模式。如果 BigDecimal 为正,则舍入行为与 ROUND_UP 相同;如果为负,则舍入行为与 ROUND_DOWN 相同。注意,此舍入模式始终不会减少计算值。

4ROUND_FLOOR接近负无穷大的舍入模式。如果 BigDecimal 为正,则舍入行为与 ROUND_DOWN 相同;如果为负,则舍入行为与 ROUND_UP 相同。注意,此舍入模式始终不会增加计算值。

5ROUND_HALF_UP向“最接近的”数字舍入,如果与两个相邻数字的距离相等,则为向上舍入的舍入模式。如果舍弃部分 >= 0.5,则舍入行为与 ROUND_UP 相同;否则舍入行ROUND_DOWN 相同。注意,这是我们大多数人在上学时就学过的舍入模式(四舍五入)。

6ROUND_HALF_DOWN向“最接近的”数字舍入,如果与两个相邻数字的距离相等,则为上舍入的舍入模式。如果舍弃部分 > 0.5,则舍入行为与 ROUND_UP 相同;否则舍入行为与 ROUND_DOWN 相同(五舍六入)。7ROUND_HALF_EVEN向“最接近的”数字舍入,如果与两个相邻数字的距离相等,则向相邻的偶数舍入。如果舍弃部分左边的数字为奇数,则舍入行为与 ROUND_HALF_UP 相同;如果为偶数,则舍入行为与 ROUND_HALF_DOWN 相同。注意,在重复进行一系列计算时,此舍入模式可以将累加错误减到最小。此舍入模式也称为“银行家舍入法”,主要在美国使用。四舍六入,五分两种情况。如果前一位为奇数,则入位,否则舍去。以下例子为保留小数点1位,那么这种舍入方式下的结果。2.35>2.4 2.45>2.48ROUND_UNNECESSARY断言请求的操作具有精确的结果,因此不需要舍入。如果对获得精确结果的操作指定此舍入模式,则抛出ArithmeticException。

public static void main(String[] args) {
  /*  double a=1.333333555555;
    double b=2.366363388888888;
    System.out.println(a*b);*/
    //对精度要求比较高,可以使用BigDecimal
    BigDecimal a = new BigDecimal("1.333333555555");
    BigDecimal b = new BigDecimal("2.366363388888888");
    BigDecimal bigDecimal = a.multiply(b);
    System.out.println(bigDecimal.toString());

    BigDecimal c = new BigDecimal("10");
    BigDecimal d = new BigDecimal("3");
   // BigDecimal divide = c.divide(d);
    BigDecimal divide = c.divide(d, 50, BigDecimal.ROUND_FLOOR);
    //ROUND_FLOOR接近负无穷大的舍入模式
    System.out.println(divide);

    System.out.println(1==0.99999999999999999999999999);

}

7.Date类的概述和方法使用

1.Date类的概述
类 Date 表示特定的瞬间,精确到毫秒。
2.构造方法
public Date()

​ public Date(long date) //把一个long类型的毫秒值转换成一个日期对象

public static void main(String[] args) {
    // 类 Date 表示特定的瞬间,精确到毫秒。
    Date date = new Date();
    System.out.println(date);
    //Tue Aug 04 16:25:37 CST 2020

   /* Date( long date)
    分配 Date 对象并初始化此对象,以表示自从标准基准时间(称为“历元(epoch)”,即 1970 年 1 月 1 日 00:00:00 GMT)以来的指定毫秒数。*/
    // 给 1970 年 1 月 1 日 00:00:00 计算机元年加上相应的时间量。
    Date date1 = new Date(1000*60*60);
    //Fri Jan 02 08:00:00 CST 1970
    System.out.println(date1);
    //Thu Jan 01 09:00:00 CST 1970(东八区)
}

3.成员方法

​ public long getTime(): 获取一个日期对象毫秒值

//1596530698532

Date ---- long 的转换:调用getTime方法

public static void main(String[] args) {
    Date date = new Date();
    //获取从 1970 年 1 月 1 日 00:00:00 到现在 所间隔的毫秒值
    long time = date.getTime();
    long l = System.currentTimeMillis();

    System.out.println(time);//1596530698532
    System.out.println(l);//1596530698532
    Date date2 = new Date();
    date2.setTime(1000*60*60*24);
    System.out.println(date2);//Fri Jan 02 08:00:00 CST 1970

    System.out.println(date.getYear());//120指的是现在距离1900多少年
    //月份由从 0 至 11 的整数表示;0 是一月、1 是二月等等;因此 11 是十二月
    System.out.println(date.getMonth());//7
}
@Deprecated //标注过时

​ public void setTime(long time): 给一个日期对象设置上指定的毫秒值 例:date.setTime(1000 * 60 * 60) ; //Fri Jan 02 08:00:00 CST 1970

long — Date 的转换:可以使用构造方法setTime(long time).

public static void main(String[] args) {
    //Date-----long
    Date date = new Date();
    long time = date.getTime();
    System.out.println(time);

    // long-----Date
    //方式1
    Date date1 = new Date(1000 * 60);
	//方式2
    Date date2 = new Date();
    date2.setTime(200000);
    System.out.println(date2);
}

8.SimpleDateFormat类实现日期和字符串的相互转换

1.SimpleDateFormat概述: 可以把一个日期对象格式化成一个文本(字符串) , 也可以把一个日期字符串解析成一个日期对象。

2.构造方法:

public SimpleDateFormat():使用默认的模式来创建一个SimpleDateFormat对象

public SimpleDateFormat(String pattern):使用指定的模式(规则比如yyyy:MM:dd HH:mm:ss)来

创建一个SimpleDateFormat对象

  • 规则的定义

  • y 年

  • M 月
  • d 天
  • H 时
  • m 分
  • s 秒

3.成员方法:

public String format(Date date): 把一个日期对象格式化成一个字符串

public Date parse(String dateStr): 把一个日期字符串解析成一个日期对象

注意要以指定格式解析

public static void main(String[] args) {
    Date date = new Date();
    System.out.println(date);//Tue Aug 04 17:19:20 CST 2020
}
public static void main(String[] args) {
    //格式化日期的一个类,可以按照我们自己喜欢的日期格式,进行格式化
    //空参构造,是按照默认格式,进行格式化
    SimpleDateFormat dateFormat = new SimpleDateFormat();
    //format(date); 把日期格式化成一个字符串
    String dateStr = dateFormat.format(date);
    System.out.println(dateStr);//20-8-4 下午5:22

    System.out.println("============================================");
    //按照我们指定的 格式来进行格式化
    SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒 E D");//E D一年的多少天
    String format = dateFormat2.format(date);
    System.out.println(format);//2020年08月04日 17时22分53秒 星期二 217

}
public static void main(String[] args) throws ParseException {
        //Date----String format(date);
        //String----Date parse(str);
        String str="2020-01-01 16:30:30";
        //注意:日期字符串和指定的格式要对应
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //把日期字符串,解析成日期对象。
        Date date = dateFormat.parse(str);
        System.out.println(date);//Wed Jan 01 16:30:30 CST 2020

}

4.例子:算一下你来到这个世界多少天。

  • a: 键盘录入一个生日(日期字符串)
  • b: 把这个日期字符串对象解析成一个日期对象
  • c: 获取b中的日期对象对应的毫秒值
  • d: 获取当前系统时间对应的毫秒值
  • e: 使用d中的毫秒值 - c中的毫秒值
  • f: 把e中的差值换算成对应的天 差值/1000/60/60/24
  • g: 输出
public static void main(String[] args) throws ParseException {
    Scanner sc = new Scanner(System.in);
    System.out.println("请输入你的生日:例如 1990-01-01");
    String birthday = sc.nextLine();
    long time = new SimpleDateFormat("yyyy-MM-dd").parse(birthday).getTime();
   // long time = DateUtils.convertStringToDate(birthday, "yyyy-MM-dd").getTime();
    long now = System.currentTimeMillis();
    System.out.println((now - time) / 1000 / 60 / 60 / 24/365+"年");

    System.out.println("=====================================================");
    //JDK1.8 提供的关于日期的类
    LocalDate birthdayDate = LocalDate.of(1995, 06, 16);
    LocalDate nowDate = LocalDate.now();
    Period period = Period.between(birthdayDate, nowDate);
    int years = period.getYears();
    int months = period.getMonths();
    int days = period.getDays();
    System.out.println(years);
    System.out.println(months);
    System.out.println(days);

}

9.Calendar类

1.Calendar类的概述和获取日期的方法

​ Calendar 类是一个**抽象类,**不能直接new对象,可以通过他的一个静态成员方法getInstance()来获取他的对象。

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

成员方法
public static Calendar getInstance() 使用默认时区和语言环境获得一个日历对象
public int get(int field) 获得给定日历字段对应的值 field通过Calendar提供的字段来拿

public static void main(String[] args) {
    Calendar rightNow = Calendar.getInstance();//一般默认当前时间的对象
    System.out.println(rightNow);
//java.util.GregorianCalendar[time=1596684993591,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=19,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2020,MONTH=7,WEEK_OF_YEAR=32,WEEK_OF_MONTH=2,DAY_OF_MONTH=6,DAY_OF_YEAR=219,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=11,HOUR_OF_DAY=11,MINUTE=36,SECOND=33,MILLISECOND=591,ZONE_OFFSET=28800000,DST_OFFSET=0]
    int year = rightNow.get(Calendar.YEAR);
    int month = rightNow.get(Calendar.MONTH);
    int day = rightNow.get(Calendar.DAY_OF_MONTH);
    int hour = rightNow.get(Calendar.HOUR);
    int minute = rightNow.get(Calendar.MINUTE);
    int s = rightNow.get(Calendar.SECOND);

    System.out.println(year + " "+month + " "+day + " "+hour + " "+minute + " "+s);
    //2020 7 6 11 36 33    月份从0开始

**public static Calendar getInstance()也可以获取指定点时间 ** 需要set方法。

2.Calendar类的add()和set()方法

public static void main(String[] args) {
    Calendar instance = Calendar.getInstance();
    //设置对应的日期。
    instance.set(Calendar.YEAR,2018);
    instance.set(Calendar.MONTH, 10);
    instance.set(Calendar.DAY_OF_MONTH,10);
    System.out.println(instance.get(Calendar.YEAR));//2018
    System.out.println(instance.get(Calendar.MONTH));//10
    System.out.println(instance.get(Calendar.DAY_OF_MONTH));//10
}
public static void main(String[] args) {
    Calendar instance2 = Calendar.getInstance();
    //add(Calendar.YEAR,-2); 给对应的日期。添加或减去相应的时间量 你传入负数,就是减去。
    instance2.add(Calendar.YEAR,-2);
    System.out.println(instance2.get(Calendar.YEAR));//2018
}

3.例题:需求:键盘录入任意一个年份,获取任意一年的二月有多少天。

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("请输入年份");
    int year = sc.nextInt();
    Calendar cal = Calendar.getInstance();
    cal.set(year,2,1);
    cal.add(Calendar.DAY_OF_MONTH,-1);//2指的是3月减去一天就是2月的最后一天
    int i = cal.get(Calendar.DAY_OF_MONTH);
    System.out.println(i);

    System.out.println("=============================");
    LocalDate of = LocalDate.of(2020, 01, 01);
    //判断是否是闰年
    boolean b = of.isLeapYear();
    System.out.println(b);
}

10. BigInteger

BigInteger概述,可以让超过long范围内的数据进行运算

1.构造方法
public BigInteger(String val)
2.成员方法
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 static void main(String[] args) {
    //BigInteger概述 可以计算超过long范围的数据
  /*  long max=Long.MAX_VALUE;
    System.out.println(max+1);*/

    BigInteger a = new BigInteger(Long.MAX_VALUE + "");
    BigInteger b = new BigInteger(Long.MAX_VALUE + "");
    BigInteger add = a.add(b);
    System.out.println(add);//18446744073709551614

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值