gpt4 book ai didi

java - 异常处理无限循环

转载 作者:太空宇宙 更新时间:2023-11-04 09:48:34 24 4
gpt4 key购买 nike

我的问题简短而有趣。我不明白为什么我的程序在捕获错误时无限循环。我做了一个新的 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());
}

}

最佳答案

您的程序将永远运行,因为在不更改扫描器状态的情况下调用 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
}

注意:在这种情况下您不需要依赖异常:您可以调用 hasNextInt() 而不是调用 nextInt() ,并检查扫描仪是否正在查看整数。

关于java - 异常处理无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55110925/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com