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