1、编写应用程序,从命令行输入表示两个小数参数的字符串,求它们的商,要求程序中捕获 NumberFormatException 异常和 ArithmeticException 异常。
import java.util.Scanner;
public class ExtDemo02 {
public static void main(String[] args) {
while (true) {
try {
System.out.println("输入两个数字:");
Scanner s = new Scanner(System.in);
double a = Double.parseDouble(s.nextLine());
double b = Double.parseDouble(s.nextLine());
if (b == 0) {
throw new ArithmeticException("除零异常,不能除0");
}
double c = a / b;
System.out.println(c);
break;
}
catch(NumberFormatException e){
System.out.println("数字格式异常");
continue;
}catch(ArithmeticException e){
System.out.println("除数不能为0");
continue;
}
}
}
}
2、编写一段程序,完善学生 student 类,增加输入学生的成绩的操作方法,如果小于 0 分或者大于 100 分则抛出异常,并捕捉异常,输出提示信息:输入的学生成绩超出范围了!
import java.util.Scanner;
public class ExtDemo02 {
public static void main(String[] args){
while(true) {
System.out.println("请输入成绩");
Scanner s = new Scanner(System.in);
int score = s.nextInt();
Student student = new Student();
student.setNo(2020189016);
student.setName("丁");
student.setAge(22);
try {
student.setScore(score);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(student);
}
}
}
class Student{
private int no;
private String name;
private int age;
private int score;
public String getScore(){
if(score>=60)
return "成绩合格";
else
return "成绩不合格";
}
public void setScore(int score) throws Exception {
if(score > 100 || score < 0) throw new Exception("输入的成绩不合理");
this.score = score;
}
public int getNo(){
return no;
}
public void setNo(int no){
this.no = no;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return age;
}
public String toString(){
return("学号:"+getNo()+",姓名:"+getName()+",年龄:"+getAge()+",成绩情况:"+getScore());
}
}