import java.util.Scanner;//导入Scanner方法
public class 超市买鸡蛋2 {//创建超市买鸡蛋2主类
public static void main(String[] args) {//主方法
try {//捕捉异常
Scanner scanner = new Scanner(System.in);//输入购买量
System.out.print("输入购买鸡蛋(斤):");//输出信息
int number = scanner.nextInt();//将购买量传给number
if(number>3){//判断number的主是否大于3
throw new RuntimeException("异常提示:这份鲜鸡蛋的重量为:"+number +",超过3斤了,超重了!!!");//抛出异常
}else {如果不满足上面的条件就执行下面代码
System.out.println("用户应支付金额"+number*3.98);//输出结果
}
}catch (Exception e){//处理异常
System.out.println(e.getMessage());//输出结果
}
}
}
结果
二、统计学校人数
代码
public class CountIsNotIntegerException extends Exception {//自定义一个异常类并继承父类Exception
public CountIsNotIntegerException (String a){//创建一个方法并传入一个字符串类型a
super(a);//调用父类的构造方法
}
}
public class 统计学校人数 {//创建类
static void school(double num)throws CountIsNotIntegerException {//定义一个方法并传入double型参数
if(num%1==0){//判断是否为整数
System.out.println("人数为"+num);//如果为整数则输出
}else{//否则执行下面的代码
throw new CountIsNotIntegerException("人数不能为小数:"+num);//抛出异常信息
}
}
public static void main(String[] args) {//主方法
try{//捕捉异常
school(456214.2);//调用方法并传入值
}catch(CountIsNotIntegerException e){//处理自定义异常
e.printStackTrace();//输出异常信息
}
}
}
一、超市特价商品采购代码import java.util.Scanner;//导入Scanner方法public class 超市买鸡蛋2 {//创建超市买鸡蛋2主类 public static void main(String[] args) {//主方法 try {//捕捉异常 Scanner scanner = new Scanner(System.in);//输入购买量 System.out.print("输入购买鸡蛋(斤):");//输出信息 int nu