使用自定义异常类的方式,当用户输入的数字大于100或小于0时,提示这是一个非法的成绩数据,让用户重新输入。
不用断言,用exception方法
import java.util.Scanner;
class MyException extends Exception{
String message;
public MyException(int score){
message = "Error,score should be in 0-100.";
}
}
class My{
public My(int s)throws MyException{
if(s>100||s<0)
{
throw new MyException(s);
}
else {
System.out.println("Your score is:"+s);
}
}
}
public class zhong{
public static void main(String[] args) throws MyException {
Scanner in=new Scanner(System.in);
System.out.println("Please input your score");
int score=in.nextInt();
try {
new My(score);
}
catch(MyException e) {
System.out.println(e.message);
}
}
}