异常后继续循环

时间:2014-08-03 04:18:21

标签: java

我有这段代码。我想回到循环的开头并再次询问用户输入。但是,它始终循环而不停止要求输入。我的代码出了什么问题?感谢

while(true){
    ... 
    try {
        int choice = input.nextInt(); <<---=- this should stop and ask for input, but it always loops without stopping.

    } catch (InputMismatchException e){
        << I want to return to the beginning of loop here >>
    }

}

6 个答案:

答案 0 :(得分:2)

来自http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt%28int%29

&#34;如果翻译成功,扫描仪将超过匹配的输入。&#34;

啊,但如果翻译成功怎么办?在这种情况下,扫描仪不会超过任何输入。糟糕的输入数据仍然是下一个要扫描的东西,因此循环的下一次迭代将像前一次一样失败 - 循环将继续尝试反复读取相同的错误输入。

为了防止无限循环,你必须超越坏数据,以便你可以获得扫描仪可以读取的整数。下面的代码片段通过调用input.next():

来完成此操作
    Scanner input = new Scanner(System.in);
    while(true){
        try {
            int choice = input.nextInt();
            System.out.println("Input was " + choice);
        } catch (InputMismatchException e){
            String bad_input = input.next();
            System.out.println("Bad input: " + bad_input);
            continue;
        }
    }

答案 1 :(得分:1)

你还没有发布任何要求输入的内容,

Scanner input = new Scanner(System.in);
int choice;
while (true) {
  System.out.println("Please enter an int: ");
  if (input.hasNextInt()) {                // <-- Check if there is an int.
    choice = input.nextInt();
    break;
  } else {
    if (!input.hasNext()) {                // <-- Check if there is input.
      System.err.println("No more input");
      System.exit(1);
    }
    // What ever is in the buffer isn't an int, print the error.
    System.out.printf("%s is not an int%n", input.next());
  }
}
// Display the choice.
System.out.printf("choice = %d%n", choice);

答案 2 :(得分:0)

这很好用:

import java.util.InputMismatchException;
import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int choice;

        while(true){
            try {
                choice = input.nextInt();
                System.out.println("Your choice: " + choice);
            } catch (InputMismatchException e){
                e.printStackTrace();
            }
        }
    }
}

答案 3 :(得分:0)

尝试做while while循环。

       do
        {
            try
            {

               //get user input
                done = true; 
            } 

            catch (InputMismatchException e)
            {
                System.out.println("The number entered needs to be a int");
            }


        } while (!done);

答案 4 :(得分:0)

这应抛出并捕获异常,continue命令应该将您发送回while loop。您需要继续或flag告诉您何时停止true

while(true)
{
try 
{
   int choice = input.nextInt();
   throw new InputMismatchException();

} 
catch (InputMismatchException e)
{
continue;
}
}

答案 5 :(得分:0)

catch块中添加行分隔符。

Scanner input = new Scanner(System.in);
while(true)
    {
        try 
        {
            int choice = input.nextInt(); 
        } catch (InputMismatchException e)
        {
            input.next(); // Line separator
        }

    }