package java第十二次作业;
import java.util.Scanner;
public class eggs {
static void hqw(int egg) throws Exception{
if(egg<11) {
throw new Exception("异常提示:这份鲜鸡蛋的重量为"+egg+"斤,超过3斤,超重了!!!");
}else {
System.out.println("在3斤以内。");
}
}
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.print("请输入新鲜鸡蛋的重量(斤):");
int egg=in.nextInt();
try {
hqw(3);
}catch(Exception e) {
System.out.println("异常提示:这份鲜鸡蛋的重量为"+egg+"斤,超过3斤,超重了!!!");
}
}
}
作业2当人数为小数时的异常提示
package java第十二次作业;
public class CountIsNotIntegerException extends Exception{
public CountIsNotIntegerException(String message) {
super(message);
}
public static void main(String[] args) {
Number count = 456214.2;
School school = new School();
school.setCount(count);
}
}
class School {
private Number count;
public void setCount(Number count) {
Integer i = count.intValue();// 把人数转为整数
Double d = count.doubleValue();// 把人数转为浮点数
double di = i;// 整数付给浮点数
if (d.equals(di)) {// 如果两个浮点数数值相同
this.count = count;
} else {// 否则抛异常
try {
throw new CountIsNotIntegerException("人数不能为小数:" + d);
} catch (CountIsNotIntegerException e) {
e.printStackTrace();
}
}
}
}