在构建一个程序,其中用户输入3到10之间的高度,并且使用java打印来自zelda的triforce。在当前时刻,只要用户输入该范围以外的数字,就会抛出异常,但是我希望程序在任何字符串输入时都抛出异常。我不知道如何利用InputMismatchException
。这是到目前为止我的代码:异常没有被执行
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int height;
try {
System.out.print("Enter height: ");
height = keyboard.nextInt();
}
catch (InputMismatchException e) {
System.out.println("");
System.out.println("Invalid height.");
}
if (height < 3 || height > 10) {
System.out.println("Invalid height.");
System.exit(0);
}
你问一个'int',如果你想检查一个字符串已经输入,然后在'扫描仪#next'或'扫描器读取# nextLine'并在try-catch块中使用'Integer#parseInt'。 –
您不应该在“错误”条件下使用'System.exit(0)':按照惯例,以零错误代码退出意味着“成功”。而且,你应该在代码中很少使用'System.exit':'return'在这里会有相同的效果。 –