一,超市特价商品采购
package 第十二次作业;
import java.util.Scanner;
public class egg {
static void ag(int age) throws Exception{
if(age<11) {
throw new Exception("异常提示:这份鲜鸡蛋的重量为"+age+"斤,超过3斤,超重了!!!");//输出信息
}else {//反正
System.out.println("在3斤以内。");//输出
}
}
public static void main(String[] args) {
Scanner in=new Scanner(System.in);//创建对象,用来输入
System.out.print("请输入新鲜鸡蛋的重量(斤):");//输出语句
double age=in.nextInt();//保存数值
try {//是否有异常
ag(3);//
}catch(Exception e) {//获取异常
System.out.println("异常提示:这份鲜鸡蛋的重量为"+age+"斤,超过3斤,超重了!!!");
}
}
}
运行结果
二,统计学校人数
package 第十二次作业;
public class CountIsNotIntegerException extends Exception {//创建自定义并继承错误
public CountIsNotIntegerException(String a) {//在方法中定义message
super(a);// 实现父类构造法方法
}
public static void main(String[] args) {
Number count = 456214.2; //定义值
School school = new School();//创建对象
school.setCount(count);//使用方法
}
}
class School {
private Number count;//调用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();//输出异常
}
}
}
}
运行结果