欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 家装 > Java异常,lambda,正则表达式

Java异常,lambda,正则表达式

2025/7/3 21:08:05 来源:https://blog.csdn.net/2302_79981885/article/details/142763926  浏览:    关键词:Java异常,lambda,正则表达式

前言

这一节讲一下异常,lambda,和正则表达式

1. 异常

1.1 见一见

在这里插入图片描述
这个是无法把abc转换为整型的,所以会报错
这个会在底部创建一个错误的对象,然后返回给虚拟机,就报错了,程序直接就终止了,没有接收异常的话

在这里插入图片描述
看这个我们就知道了,异常的根就是Throwable
Error会继承Throwable,但error是系统级别的错误,我们是用不到的
我们用的就是Exception,这个也叫做异常
分为运行时异常,RuntimeExcetion,编译阶段不会出现错误提醒,运行时如果有错才会报错,比如数组越界访问
编译时异常就是,你在编译阶段就会出现错误提醒的,比如日期解析异常
运行时异常:
在这里插入图片描述
编译时异常:
在这里插入图片描述
这就是编译时异常,还没运行,它感觉你可能会出错,所以叫你处理一下

        try {SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date d=sdf.parse("202811-11 10:12:23");System.out.println(d);} catch (ParseException e) {e.printStackTrace();}System.out.println("aaaaa");

在这里插入图片描述

第一种,方法就是去try一下,如果有错的话,有异常的话,就要被catch,printStackTrace就是打印异常信息
ParseException这个就是日期解析异常的类
被捕捉了的话,就不会直接终止掉程序了,而是会继续执行后面的代码

ctrl+alt+t可以快速创建try/catch

或者点上报错,,在alt+enter
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

第二种方法就是由main来抛出去,这个就直接抛给虚拟机了,但这个就不会执行后面的代码了,因为被虚拟机抓住了

1.2 自定义异常

因为异常有运行时异常和编译时异常,所以自定义异常也有两种
定义这两种的话,就继承它们就可以了

类继承RuntimeException就是运行时异常
继承Exception就是编译时异常

运行时异常:
在这里插入图片描述
这个需要创建构造函数,前面就可以了

public class MyRuntimeException extends RuntimeException{public MyRuntimeException() {}public MyRuntimeException(String message) {super(message);}
}
public class test1 {public static void main(String[] args) {//保存一个合法的年龄try {savaAge(160);//有异常抛出来,就要捕获了,不要留给虚拟机处理了,不要继续抛了,方法里面的异常都通通抛到main函数中捕获} catch (Exception e) {e.printStackTrace();}}public static void savaAge(int age){if(age>0&&age<150){System.out.println("年龄合法");}else{//年龄不合法,就去抛异常//new MyRuntimeException("年龄不合法");这个就是我们创建的异常对象,但这个对象要抛出去,不要放在函数里//有异常必须要抛出去的,不然就要去try捕获throw new MyRuntimeException("年龄不合法");}}
}

在这里插入图片描述

savaAge(130);

在这里插入图片描述
编译时异常:

public class MyException extends Exception{public MyException() {}public MyException(String message) {super(message);}
}

点击一个文件,ctrl+C,ctrl+v就可以复制粘贴了

在这里插入图片描述
编译时异常,你写的时候就会报错,怎么办呢,法一时try,法二是在方法那里throws

    public static void savaAge(int age) throws MyException {if(age>0&&age<150){System.out.println("年龄合法");}else{throw new MyException("年龄不合法");}}

在这里插入图片描述
这样的话,我们就普通写这个方法的时候,就会报错了,这个方法就是一个编译时异常的

要么try,要么throws

        try {savaAge(180);} catch (Exception e) {e.printStackTrace();}

在这里插入图片描述

总结一下,就是定义编译时,运行时类的时候,编译继承Exception,运行继承RuntimeException,而且都可以写两个构造方法

在写对应方法的时候,运行时就是直接new出来,throw就可以了

编译时不仅要那样,还要在方法那里throws

就这样,这两个方法就有那个样子了

在main中怎么处理异常呢,建议时try,不要throws

1.3 异常的处理1

异常的处理之一,就是抛出去,第二个处理,就是可以尝试去修复异常

抛出去的时候,可以catch多个异常,而且我们抛出去,最后都是抛在主函数中,那么就会层层抛出

public class test1 {public static void main(String[] args) {try {test1();} catch (ParseException e) {e.printStackTrace();} catch (FileNotFoundException e) {e.printStackTrace();}}public static void test1() throws ParseException, FileNotFoundException {SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date d=sdf.parse("2028-11-11 10:24:11");System.out.println(d);test2();}public static void test2() throws FileNotFoundException {InputStream is=new FileInputStream("D:QQ");//读取一个文件}
}

在这里插入图片描述

我们这个就是层层抛出的代码,都是编译时异常,test2抛给test1,test1抛给main,main再来try,catch

但是遇到了一个异常就直接跳出去了,那后面的异常就没法执行了

public class test1 {public static void main(String[] args) {try {test1();} catch (Exception e) {e.printStackTrace();} }public static void test1() throws Exception {SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date d=sdf.parse("2028-11-11 10:24");System.out.println(d);test2();}public static void test2() throws Exception {InputStream is=new FileInputStream("D:QQ");//读取一个文件}
}

在这里插入图片描述

然后就是在throws或者catch的时候,都可以用Exception来接收,因为Exception是祖先类嘛

1.4 异常的处理2

这个处理方式就是修复,比如你输入了一个错误数字,然后就会一直要求你输入正确的数字

public class test1 {public static void main(String[] args) {System.out.println(test());}public static int test(){//请输入数字,如果不正确就一直输入Scanner sc=new Scanner(System.in);while(true){System.out.println("请输入正确的数字");int a=sc.nextInt();if(a>=0){return a;}else{System.out.println("输入不合适");}}}
}

在这里插入图片描述
看这个,我们输入字母的时候就异常了,现在我们要做的就是,异常的时候,我们还要继续输入
我们输入字母的时候就异常了,所以要捕获异常

        try {System.out.println(test());} catch (Exception e) {e.printStackTrace();}

在修改

        while (true) {try {System.out.println(test());break;} catch (Exception e) {e.printStackTrace();}}

这样就可以一直输入了
因为如果异常就不会break,直接被catch了,没有异常的话,正常的话,就可以break了

1.5 finally

下面我们来讲一下finally
finally这个东西其实就是紧跟着catch的,不管是否发生了异常,finally里面的代码都会执行
如果try里面有return,在return之前执行
如果finally就是return,那么也不会影响整个函数的返回值,如果try里面有return的话
反正就是finally里面最好不要有return

2. Lambda表达式

2.1 Lambda的使用

Lambda表达式其实就是对匿名内部类的简化

public class test {public static void main(String[] args) {Animal a=new Animal(){@Overridepublic void run() {System.out.println("哈哈哈哈");}};a.run();}
}abstract class Animal{public abstract void run();
}

这个例子是匿名内部类
下面简化为Lambda表达式

public class test {public static void main(String[] args) {Animal a=()->{System.out.println("哈哈哈哈");};a.run();}
}

这个就是Lambda的形式
()里面的是参数
然后是->
后面是{}
{}里面是方法体

虽然形式书写正确,但是还是不行
在这里插入图片描述

为什么呢

因为Lambda只能简化函数式接口的匿名内部类
函数式接口就是首先为接口,然后这个接口只有一个方法,那么就是函数式接口

interface Swimming{void swim();
}

上面这个就是函数式接口

        Swimming s=new Swimming() {@Overridepublic void swim() {System.out.println("游啊游");}};s.swim();
        Swimming s=()-> {System.out.println("游啊游");};s.swim();

在这里插入图片描述
一般来说,函数式接口都有@FunctionalInterface地竹节,有这个注解的一定是函数式接口
在这里插入图片描述
还有就是我们原来讲的sort的第二个参数,也是函数式接口

      Student[]arr=new Student[4];arr[0]=new Student("aaaa",169.5,23);arr[1]=new Student("bbbb",163.8,26);arr[2]=new Student("bbbb",163.8,26);arr[3]=new Student("cccc",167.5,24);Arrays.sort(arr, new Comparator<Student>() {@Overridepublic int compare(Student o1, Student o2) {return Double.compare(o1.getHeight(),o2.getHeight());}});

这个是我原来写的代码

在这里插入图片描述
简化为

        Student[]arr=new Student[4];arr[0]=new Student("aaaa",169.5,23);arr[1]=new Student("bbbb",163.8,26);arr[2]=new Student("bbbb",163.8,26);arr[3]=new Student("cccc",167.5,24);Arrays.sort(arr, (Student o1, Student o2)-> {return Double.compare(o1.getHeight(),o2.getHeight());});System.out.println(Arrays.toString(arr));

还有

        double[]arr5={100,200,300};Arrays.setAll(arr5, new IntToDoubleFunction() {@Overridepublic double applyAsDouble(int value) {return arr5[value]*0.8;}});

在这里插入图片描述

        double[]arr5={100,200,300};Arrays.setAll(arr5,(int value)->{return arr5[value]*0.8;});System.out.println(Arrays.toString(arr5));

2.2 Lambda的再次简化

1.就是参数类型可以不写
2.如果只有一个参数的时候,参数类型可以不写,还有就是()也可以不写
3.如果方法体只有一行代码的话,大括号也可以不写,同时必须省略分号,如果是return语句的话,还必须去掉return不写

        Arrays.sort(arr, (o1,o2)-> {return Double.compare(o1.getHeight(),o2.getHeight());});Arrays.setAll(arr5,(value)->{return arr5[value]*0.8;});
        Arrays.sort(arr, (o1,o2)-> {return Double.compare(o1.getHeight(),o2.getHeight());});Arrays.setAll(arr5,value->{return arr5[value]*0.8;});
        Arrays.sort(arr, (o1,o2)-> Double.compare(o1.getHeight(),o2.getHeight()));Arrays.setAll(arr5,value->arr5[value]*0.8);

2.3 静态方法的引用

下面我们讲的引用都是针对lambda来继续简化的

        Arrays.sort(arr, (o1,o2)-> o1.getAge()-o2.getAge());

我们对这个进行简化
如果有

public class CompareByDate {public static int compareByDate(Student o1,Student o2){return o1.getAge()-o2.getAge();}
}

那么可以变为

        Arrays.sort(arr, (o1,o2)-> CompareByDate.compareByDate(o1,o2));

像这种形式的,参数一样,然后又是静态的方法->的右边,就可以静态方法引用了

        Arrays.sort(arr,CompareByDate::compareByDate);

2.4 实例方法的引用

public class CompareByDate {public int compareByDate(Student o1,Student o2){return o1.getAge()-o2.getAge();}
}
Arrays.sort(arr, (o1,o2)-> o1.getAge()-o2.getAge());
        CompareByDate compare=new CompareByDate();Arrays.sort(arr, (o1,o2)-> compare.compareByDate(o1,o2));
        CompareByDate compare=new CompareByDate();Arrays.sort(arr, compare::compareByDate);

2.5 特定类型的方法引用

        String[]name={"bady","angle","Andy","dlei","caocao","Babo","jack","Cici"};Arrays.sort(name);System.out.println(Arrays.toString(name));

在这里插入图片描述
这个是默认用ASCII来排序的

下面我们来要求忽略大小写来排序

        Arrays.sort(name, new Comparator<String>() {@Overridepublic int compare(String o1, String o2) {return o1.compareToIgnoreCase(o2);}});

在这里插入图片描述
优化

        Arrays.sort(name,(String o1, String o2) ->{return o1.compareToIgnoreCase(o2);});
        Arrays.sort(name,( o1,  o2) -> o1.compareToIgnoreCase(o2));

compareToIgnoreCase就叫做特定类型的引用

第一个参数是主调,后面的全部参数都是主调的参数,那么这个就是特定类型的引用,是满足特定类型的引用的

        Arrays.sort(name,String::compareToIgnoreCase);

2.6 构造器引用


public class Car {private String name;private double price;public Car(){}@Overridepublic String toString() {return "Car{" +"name='" + name + '\'' +", price=" + price +'}';}public Car(String name, double price) {this.price = price;this.name = name;}public void setPrice(double price) {this.price = price;}public void setName(String name) {this.name = name;}public String getName() {return name;}public double getPrice() {return price;}
}
interface CreateCar {Car create(String name,double price);
}
public class test1 {public static void main(String[] args) {CreateCar cc=new CreateCar(){@Overridepublic Car create(String name, double price) {return new Car(name,price);}};Car car=cc.create("aaaa",12);System.out.println(car);}
}

在这里插入图片描述
这个的匿名内部类是创造一个对象
继续优化

        CreateCar cc=(name, price)-> new Car(name,price);

这样的类型就可以优化为构造器引用了

        CreateCar cc=Car::new;
        CreateCar cc=Car::new;Car car=cc.create("aaaa",12);System.out.println(car);

在这里插入图片描述

2.7 补充

这里补充一个方法

        int[]arr={2,3,4,5,6,7,9,0,8,7,6,6,5,54,1,45,65,34};System.out.println(Arrays.binarySearch(arr, 54));

在这里插入图片描述

binarySearch这个其实就是折半查找

3. 正则表达式

3.1 见一见

public class test1 {public static void main(String[] args) {System.out.println(checkQQ("1111111111"));}//输入一个字符串,判断是不是QQ号码public static boolean checkQQ(String qq){if(qq==null||qq.startsWith("0")||qq.length()<6||qq.length()>20){return false;}for (int i = 1; i < qq.length(); i++) {char c=qq.charAt(i);if(c<'0'||c>'9'){return false;}}return true;}
}

在这里插入图片描述

public class test1 {public static void main(String[] args) {System.out.println(checkQQ("11111aaa1111"));}//输入一个字符串,判断是不是QQ号码public static boolean checkQQ(String qq){//return qq!=null&&qq.matches("正则表达式");return qq!=null&&qq.matches("[1-9]\\d{5,19}");}
}

在这里插入图片描述

3.2 学习很多的正则表达式

        System.out.println("a".matches("[abc]"));//[]表示只能匹配一个字符,然后这个的意思就是匹配abc中的一个即可System.out.println("e".matches("[abc]"));//falseSystem.out.println("d".matches("[^abc]"));//表示不能是abc中的任意一个System.out.println("a".matches("[^abc]"));//falseSystem.out.println("b".matches("[a-zA-Z]"));//表示为a-z或者A-Z中的一个字符都可以System.out.println("2".matches("[a-zA-Z]"));//falseSystem.out.println("k".matches("[a-z&&[^bc]]"));//a-z除了bcSystem.out.println("b".matches("[a-z&&[^bc]]"));//falseSystem.out.println("ab".matches("[a-zA-Z0-9]"));//falseSystem.out.println("徐".matches("."));//可以匹配任意字符,一个字符System.out.println("徐a".matches("."));//falseSystem.out.println("\"");//   \有特殊含义,必须要转义//System.out.println("3".matches("\d"));//  \d表示整数,但是\有特殊含义,为了让他就是一个\,我们就要转义才行System.out.println("3".matches("\\d"));//  \d表示整数,但是\有特殊含义,为了让他就是一个\,我们就要转义才行System.out.println("a".matches("\\d"));//falseSystem.out.println(" ".matches("\\s"));//表示一个空白字符System.out.println("a".matches("\\s"));//flaseSystem.out.println("3".matches("\\S"));//表示非空白字符System.out.println(" ".matches("\\S"));//falseSystem.out.println("3".matches("\\w"));//表示数字或者字母a-zA-Z0-9System.out.println("_".matches("\\w"));//表示数字或者字母a-zA-Z0-9还有下划线_///trueSystem.out.println("哈".matches("\\w"));//falseSystem.out.println("哈".matches("\\W"));//表示不是a-zA-Z0-9_System.out.println("a".matches("\\W"));//falseSystem.out.println("234".matches("\\d"));//这些预定义字符都只适合一个字符、、、false//数量词System.out.println("a".matches("\\w?"));//代表0个或者1个System.out.println("".matches("\\w?"));System.out.println("abc".matches("\\w?"));//falseSystem.out.println("abc".matches("\\w*"));//代表0次或者多次System.out.println("".matches("\\w*"));//System.out.println("abc章".matches("\\w*"));//falseSystem.out.println("abc12".matches("\\w+"));//代表1次或者多次System.out.println("".matches("\\w+"));//代表1次或者多次System.out.println("abc哈".matches("\\w?"));//falseSystem.out.println("abc".matches("\\w{3}"));//正好是三次System.out.println("aabc".matches("\\w{3}"));//flaseSystem.out.println("aabca".matches("\\w{3,}"));//大于等于3次System.out.println("aa".matches("\\w{3,}"));//flaseSystem.out.println("aaaaa".matches("\\w{3,9}"));//3-9次//其他字符  (?i)忽略大小写  |或    ()分组System.out.println("abc".matches("(?i)abc"));//忽略大小写System.out.println("aBC".matches("(?i)abc"));//trueSystem.out.println("aBc".matches("a((?i)b)c"));//只对b忽略大小写System.out.println("aBC".matches("a((?i)b)c"));//false//需求1,要么是三个小写字母,要么是三个数字System.out.println("123".matches("\\d{3}|[a-z]{3}"));//需求2:必须是“我爱”开头,中间至少一个编程,最后至少一个666System.out.println("我爱编程666".matches("我爱(编程)+(666)+"));System.out.println("我爱编程6666".matches("我爱(编程)+(666)+"));//false

3.3 应用

    public static void checkPhone(){System.out.println("请输入手机号");Scanner sc=new Scanner(System.in);while (true) {String phone=sc.nextLine();//手机号:1324567854  座机:010-11224  010123525if(phone.matches("1[3-9]\\d{9}|(0\\d{2,7}-?[1-9]\\d{4,19})")){System.out.println("输入正确");break;}else{System.out.println("输入不正确");}}}
    public static void main(String[] args) {//把一段内容里面的电话号码拿出来String data="17381443641"+"aaaaaaaaa"+"12345678901"+"bbbbbbbbbbbbbbbbbbb"+"13425678901"+"bbbbbbbbbbbbb";//定义正则表达式String regex="1[3-9]\\d{9}|(0\\\\d{2,7}-?[1-9]\\d{4,19})";//把正则表达式分装成对象,,是Pattern类Pattern pattern=Pattern.compile(regex);//通过pattern得到匹配器Matcher matcher=pattern.matcher(data);//开始查找while(matcher.find()){System.out.println(matcher.group());}}

在这里插入图片描述

        String s1="哈哈哈哈aaaaa不不不不不不bbbbbb擦擦擦擦擦擦kkkkkk";System.out.println(s1.replaceAll("\\w+", "-"));

在这里插入图片描述

在这里插入图片描述
把.括起来表示这是一个组,然后+就表示这个组出现了多次

public class test1 {public static void main(String[] args) {//把重复的字换成一个字String s2="我我我我我我爱爱爱爱爱爱爱便便便便";System.out.println(s2.replaceAll("(.)\\1+", "$1"));//(.)   对.分成一个组    +表示这个组出现了多次    这个组就是任意字符  表示这个字符出现了多次//  \\1  表示对这个组命名为组1   $1就是取这个组1里面的内容}
}

在这里插入图片描述

public class test1 {public static void main(String[] args) {//把中文提取出来String s1="哈哈哈哈aaaaa不不不不不不bbbbbb擦擦擦擦擦擦kkkkkk";String[] arr=s1.split("\\w+");//以\w+进行分割,返回分割后的数组集合System.out.println(Arrays.toString(arr));}
}

在这里插入图片描述

总结

下一节讲一些集合框架

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词