一、作业要求:
接收用户输入分数信息,如果分数在0—100之间, 输出成绩。
如果成绩不在该范围内, 抛出异常信息,提示分数必须在0—100之间。
二、代码实现
(一)代码:
package task_07_Exception_Thread;
import java.util.Scanner;
public class IllegalScoreException extends Exception
{
// 带有错误信息的构造方法
public IllegalScoreException(String msg) {
// 调用Exception类中有一个参数的构造方法传递错误信息
super(msg);
}
// 检查输入分数是否在0-100之间,如果不是则抛出自定义异常IllegalScoreException!
// 注意:在方法内抛出的检查性异常需要在方法头throws交给调用方法处捕获处理!
public static void checkScore(float score) throws IllegalScoreException
{
if(score<0||score>100) {
throw new IllegalScoreException("输入错误提醒 --> 您输入的分数 "+score+" 不在0-100之间!必须输入在0—100之间的成绩!");
}
}
// 接收并返回控制台输入的字符串的方法
static String consoleInput(Scanner sc) {
String inputStr = null;
if(sc.hasNextLine()) {
inputStr = sc.nextLine();
}
return inputStr;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
float score;
while(true) {
System.out.print("请输入分数(退出请输入e):");
String inputStr = consoleInput(sc);
if(inputStr !=null && inputStr.equals("e")) {
System.out.println("已退出!");
break;
}
else
try {
score = Float.parseFloat(inputStr);
checkScore(score);
System.out.println("您输入的成绩为:" + score);
}catch(NumberFormatException e) { // 捕获输入分数非数字的NumberFormatException
System.out.println("输入错误提醒 --> 您输入的分数 "+inputStr+" 不是数字!");
}catch(IllegalScoreException e) { // 捕获输入分数不是0-100之间的IllegalScoreException
System.out.println(e);
}
}
sc.close();
}
}
(二)、运行结果: