异常处理无限循环

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

}

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

以上是 异常处理无限循环 的全部内容, 来源链接: utcz.com/qa/399311.html

回到顶部