lambda和异常
(一) Lambda
引入Lambda
1.用匿名内部类实现
我们都知道,每个java文件必须有一个与这个java文件同名的外部类,这个外部类可以是public或default的。而除了这个同名外部类,还可以有与这个同名外部类平级的其他外部类,但它们必须是default的。
而内部类是指在外部类的内部再定义一个类。
package work1;
//定义动物类接口
interface Animal {
void shout();
}
public class Example21 {
public static void main(String[] args) {
String name = "小花";
// 定义匿名内部类作为参数传递给animalShout()方法
animalShout(new Animal() {
// 实现shout()方法
public void shout() {
// JDK 8开始,局部内部类、匿名内部类可以访问非final的局部变量
System.out.println(name + "喵喵...");
}
});
}
// 定义静态方法animalShout(),接收接口类型参数
public static void animalShout(Animal an) {
an.shout(); // 调用传入对象an的shout()方法
}
}
Lambda表达式实现
package work2;
//定义动物类接口
interface Animal {
void shout(); // 定义方法shout()
}
public class Example22 {
public static void main(String[] args) {
String name = "小花";
// 1、匿名内部类作为参数传递给animalShout()方法
animalShout(new Animal() {
public void shout() {
System.out.println("匿名内部类输出:" + name + "喵喵...");
}
});
// 2、使用Lambda表达式作为参数传递给animalShout()方法
animalShout(() -> System.out.println("Lambda表达式输出:" + name + "喵喵..."));
}
// 创建一个animalShout()静态方法,接收接口类型的参数
public static void animalShout(Animal an) {
an.shout();
}
}
2、用Lambda表达式实现接口中两个函数的调用测试。
package week15;
//定义无参、无返回值的函数式接口
@FunctionalInterface
interface Animal {
void shout();
}
//定义有参、有返回值的函数式接口
interface Calculate {
int sum(int a, int b);
}
public class Example23 {
public static void main(String[] args) {
// 分别两个函数式接口进行测试
animalShout(() -> System.out.println("无参、无返回值的函数式接口调用"));
showSum(10, 20, (x, y) -> x + y);
}
// 创建一个动物叫的方法,并传入接口对象Animal作为参数
private static void animalShout(Animal animal) {
animal.shout();
}
// 创建一个求和的方法,并传入两个int类型以及接口Calculate类型的参数
private static void showSum(int x, int y, Calculate calculate) {
System.out.println(x + "+" + y + "的和为:" + calculate.sum(x, y));
}
}
3、验证下列程序,掌握其方法。
package week15;
//定义一个函数式接口
@FunctionalInterface
interface Calcable {
int calc(int num);
}
//定义一个类,并在类中定义一个静态方法
class Math {
// 定义一个求绝对值方法
public static int abs(int num) {
if (num < 0) {
return -num;
} else {
return num;
}
}
}
//定义测试类
public class Example24 {
private static void printAbs(int num, Calcable
calcable) {
System.out.println(calcable.calc(num));
}
public static void main(String[] args) {
// 使用Lambda表达式方式
printAbs(-10, n -> Math.abs(n));
// 使用方法引用的方式
printAbs(-10, Math::abs);
}
}
4、验证下列程序,掌握其方法。
package week15;
//定义一个函数式接口
@FunctionalInterface
interface Printable{
void print(String str);
}
class StringUtils {
public void printUpperCase(String str) {
System.out.println(str.toUpperCase());
}
}
//定义测试类
public class Example25 {
private static void printUpper(String text, Printable pt) {
pt.print(text);
}
public static void main(String[] args) {
StringUtils stu = new StringUtils();
// 使用Lambda表达式方式
printUpper("Hello", t -> stu.printUpperCase(t));
// 使用方法引用的方式
printUpper("Hello", stu::printUpperCase);
}
}
5、验证下列程序,掌握其方法。
package week15;
//定义一个函数式接口
@FunctionalInterface
interface PersonBuilder {
Person buildPerson(String name);
}
//定义一个Person类,并添加有参构造方法
class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
//定义测试类
public class Example26 {
public static void printName(String name, PersonBuilder builder) {
System.out.println(builder.buildPerson(name).getName());
}
public static void main(String[] args) {
// 使用Lambda表达式方式
printName("夏侯惇", name -> new Person(name));
// 使用构造器引用的方式
printName("夏侯惇", Person::new);
}
}
6、验证下列程序,掌握其方法。
package week15;
//定义一个函数式接口
@FunctionalInterface
interface Printable{
void print(StringUtils su, String str);
}
class StringUtils {
public void printUpperCase(String str) {
System.out.println(str.toUpperCase());
}
}
//定义测试类
public class Example27 {
private static void printUpper(StringUtils su, String text,
Printable pt) {
pt.print(su, text);
}
public static void main(String[] args) {
// 使用Lambda表达式方式
printUpper(new StringUtils(), "Hello",
(object, t) -> object.printUpperCase(t));
// 使用方法引用的方式
printUpper(new StringUtils(), "Hello",
StringUtils::printUpperCase);
}
}
(二)异常
7、异常的基础练习1,回答能否将几个catch语句交换位置,并回答为什么。
基本结构一 基本机构二
class Exce{
public int div(int a,int b) throws Exception{
// try{
return a/b;
// }catch(Exception e){
// e.printStackTrace();
// System.out.println(e.getMessage());
// return 0;
// }
// return a/b;
}
}
class MyException03 {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Exce exce01=new Exce();
try{
exce01.div(100,0);
}
catch(ArithmeticException e){
System.out.println("出现异常");
e.printStackTrace();
System.out.println(e.getMessage());
System.out.println(e.toString());
}catch(Exception e){
System.out.println("出现异常");
}
// exce01.div(100,0);
System.out.println("出现异常");
}
}
public class ExDemo2 {
static void calculate() throws IllegalAccessException{
int c[]={1,2};
c[1]=60;
int a=100;
System.out.println("a="+a);
int b=50/a;
throw new IllegalAccessException();
}
public static void main(String args[]){
try {
calculate();
}
catch(IllegalAccessException e){
System.out.println("非法存取:"+e);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("数组越界:"+e);
}
catch(ArithmeticException e){
System.out.println("被0整除:"+e);
}
finally{
System.out.println("最后执行的语句!");
}
}
}
8、异常基础练习2,回答为什么“t没有机会赋值”,并回答为什么。
public class Exception01 {
/**
* @param args
*/
public static void main(String args[ ]) {
int n=0,m=0,t=6666;
try{ m=Integer.parseInt("8888");
n=Integer.parseInt("ab85"); //发生异常,转向catch
t=9999; //t没有机会赋值
}
catch(NumberFormatException e) {
System.out.println("发生异常:"+e.getMessage());
n=123;
}
System.out.println("n="+n+",m="+m+",t="+t);
}
}
9、finally语句结构;
public class Exception2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
int x = args.length, y = 222, z;
z = y / x;
System.out.println("x除以y的值是:" + z);
} catch (ArithmeticException e) {
System.out.println("捕获到了算术异常!" + e);
} finally {
System.out.println("现在执行到finally子句了。");
try {
String strName = null;
if (strName.equals("锄禾日当午"))
System.out.println(strName + "汗滴禾下土");
} catch (Throwable e) {
System.out.print("又捕获到一个异常!" + e);
} finally {
System.out.print(",又执行到一个finally子句了。");
}
}
}
}
10、Throws语句
public class Exception3 {
/**
* @param args
* throws的使用
*/
static void ArrayTest(int x) throws ArithmeticException,
ArrayIndexOutOfBoundsException {
System.out.print("i=" + x);
if (x == 111) {
System.out.println(" , 此时尚无异常发生!");
return;
}
if (x == 3) {
int array[] = new int[6];
array[20] = 200;
}
}
public static void main(String args[]) {
try {
ArrayTest(111);
ArrayTest(3);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.print(" , 数组越界异常被捕获:");
System.out.println(e);
} catch (ArithmeticException e) {
System.out.println("算术异常被捕获 " + e);
} finally {
System.out.print("执行到了finally子句!");
}
}
}
问:ArrayTest(111);ArrayTest(3);两句不用try_catch语句包裹会如何?
11、自定义异常+抛出异常练习。(自定义异常类+throw语句)
class MyException extends Exception {//继承异常类,完成自定义异常类的定义
private int x;
MyException(int a) {
x = a;
}
public String toString() {
return "MyException";
}
}
public class Exception5 {
/**
* @param args
* 本例为自定义异常示例
*/
static void method(int a) throws MyException {
System.out.print("此处引用mathod(" + a + ")");
if (a > 10)
throw new MyException(a);
System.out.println(" , 正常返回!");
}
public static void main(String args[]) {
try {
System.out.print("进入监控区,执行此段程序可能发生异常!");
method(8);
method(20);
method(6);
} catch (MyException e) {
System.out.print(" ,程序发生异常就在此处处理;");
System.out.println("所发生的异常是:" + e.toString() + "。");
System.out.print("在此可以执行其它代码!");
}
}
}
12、自定义异常+抛出异常练习。(自定义异常类+throw语句)
import java.util.Scanner;
public class ExceptionExe {
int score;
/**
* @param args
*/
public void setScore(){
System.out.println("请输入学生的成绩");
Scanner readScore=new Scanner(System.in);
score=readScore.nextInt();
}
public int getScore(){
return score;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ExceptionExe e01=new ExceptionExe();
try{
e01.setScore();
if(e01.getScore()<0||e01.getScore()>100){
System.out.println("输入成绩不合理。");
throw new ScoreException(e01.getScore());
}else
System.out.printf("学生成绩= %d",e01.getScore());
}catch(ScoreException e){
System.out.println("自己定义的\"输入成绩不合理\"的提示。");
}
}
}
class ScoreException extends Exception {
String message;
public ScoreException(int s) {
message="成绩"+s+"不合理";
}
public String toString() {
return message;
}
}