目录
1.超市特价商品采购
2.统计学校人数
1.超市特价商品采购
import java.util.Scanner;//导入import java.util.Scanner包
public class CS {
static void avg(int a) throws MyException{
System.out.println("请输入鲜鸡蛋的重量(斤):");
Scanner scanner=new Scanner(System.in);//从键盘获取输入的值放入scanner
int a1=scanner.nextInt();//把scanner的值赋予给a
if(a1>=10) {
throw new MyException("");
}else {System.out.println("异常提示:"+"这份鲜鸡蛋的重量为10.0斤");
}}
public static void main(String[] args) {
try {
avg(10);
}catch(MyException e) {
System.out.println("异常提示:"+"这份鲜鸡蛋的重量为10.0斤");
}
}
}
2.统计学校人数
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条)