总结经典异常

2021.02.22
第十六次记录
课堂记录:
总结经典异常:
空指针异常:NullPointerException
类型转换异常:ClassCastException
数组下标越界异常:IndexOutOfBoundsException
数字格式化异常:.NumberFormatException

代码演示1:

public class IntegerText06 {
    
    
    public static void main(String[] args) {
    
    
        //手动装箱
        Integer x = new Integer(1000);
        //手动拆箱
        int y = x.intValue();
        System.out.println(y);
        //编译没问题,运行会出异常
        //数字格式化异常:java.lang.NumberFormatException
        //int a = new Integer("中国人");  里面至少是数字,不能是中文
        System.out.println("------------------");
        //重点方法:static int parseInt(String s)
        //静态方法,传参String,返回int
        int b = Integer.parseInt("123");//String--->int
        //直接做求和运算
        System.out.println(b + 100);
        //double类型也是如此,其他类型也一样
        System.out.println(100 + Double.parseDouble("5"));
        System.out.println(Float.parseFloat("3.14"));
    }
}

输出结果:
1000
223
105.0
3.14

代码演示2:

/*
int Integer String之间的相互转换
*/
public class IntegerText07 {
    
    
    public static void main(String[] args) {
    
    
        //String--->int
        String s1 = "100";
        int i1 = Integer.parseInt(s1);
        System.out.println(i1);
        //int--->String
        String s2 = i1 + "";
        System.out.println(s2 + 1);
        //int--->Integer
        //自动装箱
        Integer x = 100;
        //Integer--->int
        //自动拆箱
        int y = x;
        System.out.println(y);
        //String--->Integer
        Integer a = Integer.valueOf("123");
        System.out.println(a);
        //Integer--->String
        String b = String.valueOf(a);
        System.out.println(b);
    }
}

输出结果:
100
1001
100
123
123

猜你喜欢

转载自blog.csdn.net/qq_55171059/article/details/113953901