一、超市采购
代码:
import java.util.Scanner;
public class Caigou {
public static void main(String[] args) {
System.out.println("请输入鲜鸡蛋的重量(斤):");
Scanner a=new Scanner(System.in);
int egg=a.nextInt();
if(egg<=7){
System.out.println("应付"+egg*3.98+"元");
}else{
try{
int ar=Integer.parseInt("24的");
}catch(Exception e){
System.out.println("异常提示:这份鲜鸡蛋的重量为"+egg+"斤,超出3斤,超重了!!!");
}
}
}
}
运行结果:
二、统计学校人数
代码:
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();
}
}
}
}
运行结果:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)