在实验1基础上,
定义一个异常类ScoreException,当输入的学生成绩不在[0,100]区间时,抛出该异常。
定义一个异常类StudentNumberException,当输入的学号不满足下述条件,则抛出该异常。条件为:学号为10位,第1位为2,第2位为0,其余位为数字0~9.
对Student和StudentTest类进行必要修改,提升程序的健壮性。
StudentTest类运行效果如下:
测试用例1:
1011211301 WangXiao 85 75 95
Illegal number format
测试用例2:
2011211301 WangXiao 859 75 95
Illegal score format
测试用例3:
2011211301 WangXiao 85 75 95
Student Info:
Number:2011211301
Name:WangXiao
Math:85
English:75
Science:95
Ave:85.00
import java.text.DecimalFormat;
import java.util.Scanner;
class Score extends Exception
{
public Score()
{
System.out.println("Illegal score format");
}
}
class StudentNumber extends Exception
{
public StudentNumber()
{
System.out.println(("Illegal number format"));
}
}
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String student_number = in.next();
String student_name = in.next();
int Math = in.nextInt();
int English = in.nextInt();
int Science = in.nextInt();
int logic = 1;
char[] num = student_number.toCharArray();
try {
//System.out.println(Math);
for (int i = 0; i < student_number.length(); i++) {
if (num[i] < '0' || num[i] > '9') {
//System.out.println(num[i]);
logic = 0;
//System.out.println(logic);
}
}
if (num[0] != '2' || num[1] !='0' ) {
logic = 0;
}
//System.out.println(Math);
//System.out.println(logic);
if (logic == 1 && Math >= 0 && Math <= 100 && English <= 100 && English >= 0 && Science >= 0 && Science <= 100) {
double average = (Math + Science + English) / 3.0;
// System.out.println("我一点也不热爱这里");//2011211301 WangXiao 85 75 95
DecimalFormat a = new DecimalFormat("#.00");
System.out.println("Student Info:");
System.out.println("Number:" + student_number);
System.out.println("Name:" + student_name);
System.out.println("Math:" + Math);
System.out.println("English:" + English);
System.out.println("Science:" + Science);
System.out.println("Ave:" + a.format(average));
} else if (logic == 0 || num[0] != '2' || num[1] != '0') {
throw new StudentNumber();
} else {
throw new Score();
}
}
catch (Exception e) {
}
}
}
注意写异常类的构造函数的时候不要加返回值类型,即便是void也不能加。
构造函数没有返回值,也不能用void修饰. 如果不小心给构造函数前面添加了返回值类型,那么这将使这个构造函数变成一个普通的方法,在运行时将产生找不到构造方法的错误。
网上找到的,基础不牢地动山摇