首先,我只想说,我知道这个程序可以通过使用 if-else 配置或 while 循环更容易地完成,但我想知道如何使用异常类来完成它。(我猜我需要使用 try-catch 块的自定义异常)。
import java.util.Scanner;
class AgeChecker
{
public static void main(String [] args)
{
Scanner inputdata = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = inputdata.nextLine();
System.out.print(name+", enter your age: ");
int age = inputdata.nextInt();
try
{ // age entered must be between 0-125 (how to trigger exception in catch block?)
System.out.println("You entered: "+age);
}
catch(Exception e)
{
System.out.println("Out of range error! (must be between ages 0 and 125)"+e);
}
finally
{
System.out.println("Age Checking Complete.");
}
}
}