我的问题简短而且甜蜜。我不明白为什么我的程序在捕获错误时无限循环。我做了一个新的try-catch语句,但它循环甚至复制,粘贴和修改了之前有效的程序中的相应变量。以下是声明本身及以下将是整个计划。谢谢你的帮助!
try {
input = keyboard.nextInt();
}
catch(Exception e) {
System.out.println("Error: invalid input");
again = true;
}
if (input >0 && input <=10)
again = false;
}
程序:
public class Blanco {
public static int input;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
nameInput();
}
/**
*
* @param name
*/
public static void nameInput() {
System.out.println("What is the name of the cartoon character : ");
Scanner keyboard = new Scanner(System.in);
CartoonStar star = new CartoonStar();
String name = keyboard.next();
star.setName(name);
typeInput(keyboard, star);
}
public static void typeInput(Scanner keyboard, CartoonStar star) {
boolean again = true;
while(again){
System.out.println("What is the cartoon character type: 1 = FOX,2 = CHICKEN,3 = RABBIT,4 = MOUSE,5 = DOG,\n"
+ "6 = CAT,7 = BIRD,8 = FISH,9 = DUCK,10 = RAT");
try {
input = keyboard.nextInt();
}
catch(Exception e) {
System.out.println("Error: invalid input");
again = true;
}
if (input >0 && input <=10)
again = false;
}
switch (input) {
case 1:
star.setType(CartoonType.FOX);
break;
case 2:
star.setType(CartoonType.CHICKEN);
break;
case 3:
star.setType(CartoonType.RABBIT);
break;
case 4:
star.setType(CartoonType.MOUSE);
break;
case 5:
star.setType(CartoonType.DOG);
break;
case 6:
star.setType(CartoonType.CAT);
break;
case 7:
star.setType(CartoonType.BIRD);
break;
case 8:
star.setType(CartoonType.FISH);
break;
case 9:
star.setType(CartoonType.DUCK);
break;
case 10:
star.setType(CartoonType.RAT);
break;
}
popularityNumber(keyboard, star);
}
public static void popularityNumber(Scanner keyboard, CartoonStar star) {
System.out.println("What is the cartoon popularity number?");
int popularity = keyboard.nextInt();
star.setPopularityIndex(popularity);
System.out.println(star.getName() + star.getType() + star.getPopularityIndex());
}
}
答案 0 :(得分:3)
您的程序将永远运行,因为在不更改扫描程序状态的情况下调用nextInt
会一次又一次地导致异常:如果用户未输入int
,则调用keyboard.nextInt()
不会更改扫描仪正在查看的内容,因此当您在下一次迭代中调用keyboard.nextInt()
时,您将获得异常。
您需要添加一些代码来读取用户在处理异常后输入的垃圾以解决此问题:
try {
...
} catch(Exception e) {
System.out.println("Error: invalid input:" + e.getMessage());
again = true;
keyboard.next(); // Ignore whatever is entered
}
注意:在这种情况下你不需要依赖异常:而不是调用nextInt()
,你可以调用hasNextInt()
,并检查扫描程序是否正在查看整数。