|
@@ -0,0 +1,113 @@
|
|
|
+package com.sf.day09;
|
|
|
+
|
|
|
+
|
|
|
+import org.junit.Test;
|
|
|
+
|
|
|
+import java.util.ArrayList;
|
|
|
+import java.util.Arrays;
|
|
|
+import java.util.List;
|
|
|
+import java.util.function.Consumer;
|
|
|
+import java.util.function.Predicate;
|
|
|
+import java.util.function.Supplier;
|
|
|
+
|
|
|
+public class Te1 {
|
|
|
+ public static void main(String[] args) throws Exception {
|
|
|
+ shop(500, money -> System.out.println("消费"+ money+"元"));
|
|
|
+
|
|
|
+ shop(500, System.out::println);
|
|
|
+
|
|
|
+ getCode(5,() -> (int)Math.random()*10);
|
|
|
+
|
|
|
+ List<String> list = Arrays.asList("hsajfha", "fia", "fail", "fjaoi", "fauj");
|
|
|
+ getString(list, s -> s.length()>5);
|
|
|
+
|
|
|
+ int tect = tect("abc"); //“123”
|
|
|
+ System.out.println(tect);
|
|
|
+ }
|
|
|
+ /**
|
|
|
+ * 编写 shop 方法输出消费多少元
|
|
|
+ */
|
|
|
+ public static void shop(int money, Consumer<Integer> consumer){
|
|
|
+ consumer.accept(money);
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 编写 getCode 方法返回指定位数的随机验证码字符串
|
|
|
+ * number : 位数
|
|
|
+ */
|
|
|
+ public static String getCode(int number, Supplier<Integer> supplier){
|
|
|
+ StringBuilder stringBuilder = new StringBuilder();
|
|
|
+ for (int i = 0;i<number;i++){
|
|
|
+ stringBuilder.append(supplier.get());
|
|
|
+ }
|
|
|
+ return stringBuilder.toString();
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 编写 getString 方法返回长度大于5的字符串的集合**
|
|
|
+ */
|
|
|
+ public static List<String> getString(List<String> list , Predicate<String> predicate){
|
|
|
+ List<String> list1 = new ArrayList<>();
|
|
|
+ for (String s : list) {
|
|
|
+ if(predicate.test(s)){
|
|
|
+ list1.add(s);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return list1;
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test
|
|
|
+ public void t1() {
|
|
|
+ try {
|
|
|
+ Thread.sleep(12);
|
|
|
+ int a = 1/0;
|
|
|
+ } catch (Exception e) {
|
|
|
+ throw new RuntimeException(e);
|
|
|
+ }
|
|
|
+
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test
|
|
|
+ public void t2(){
|
|
|
+ try{
|
|
|
+ String str1 = "lc.com";
|
|
|
+ str1 = null;
|
|
|
+ System.out.println(str1.charAt(0));
|
|
|
+ }catch(NullPointerException e){
|
|
|
+ //异常的处理方式1
|
|
|
+ System.out.println("不好意思,亲~出现了小问题,正在加紧解决...");
|
|
|
+ }catch(ClassCastException e){
|
|
|
+ //异常的处理方式2
|
|
|
+ System.out.println("出现了类型转换的异常");
|
|
|
+ }catch(RuntimeException e){
|
|
|
+ //异常的处理方式3
|
|
|
+ System.out.println("出现了运行时异常");
|
|
|
+ }
|
|
|
+ //此处的代码,在异常被处理了以后,是可以正常执行的
|
|
|
+ System.out.println("hello");
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+ public static int tect(String str) throws Exception{
|
|
|
+// try {
|
|
|
+// Integer.parseInt(str);
|
|
|
+// return 1;
|
|
|
+// }catch (NumberFormatException e){
|
|
|
+// return -1;
|
|
|
+// }finally {
|
|
|
+// System.out.println("end~");
|
|
|
+// return 0;
|
|
|
+// }
|
|
|
+
|
|
|
+ int i = 100;
|
|
|
+ try {
|
|
|
+ return i;
|
|
|
+ } finally {
|
|
|
+ return ++i;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+}
|