无尽的java循环,同时采取输入

时间:2014-05-16 12:47:52

标签: java loops while-loop infinite-loop

我在这里有一个while循环这个问题:

while((input = InputHandler.getInt()) != 1 && input != 2){
        if(input == InputHandler.CODE_ERROR)
            System.out.print("Input must be a number");
    }

这个while循环只接受一次输入,并且不再要求它,所以它循环使用整个时间输入的输入。我在这里做错了什么,因为对我而言,这个诡计循环是否真的很奇怪?

InputHandler类:

public class InputHandler {
  public static Scanner in = new Scanner(System.in);
  public static int CODE_ERROR = -6;

  public static int getInt(){
    try{
        return in.nextInt();
    } catch(InputMismatchException e){
        return CODE_ERROR;
    }
  }
}

2 个答案:

答案 0 :(得分:5)

目前,如果在命令行输入非整数,您的代码将进入无限循环。这是因为您的in.nextInt()方法引发了异常并且在扫描程序中留下了有问题的值

您需要通过调用in.next();来使用导致异常的无效令牌:

public static void main(String[] args) throws Exception {
    int input;
    while ((input = InputHandler.getInt()) != 1 && input != 2) {
        if (input == InputHandler.CODE_ERROR)
            System.out.print("Input must be a number");
    }
}

public static class InputHandler {
    public static Scanner in = new Scanner(System.in);
    public static int CODE_ERROR = -6;

    public static int getInt(){
      try{
          return in.nextInt();
      } catch(InputMismatchException e){
          in.next();  // <------------------ this should solve it
          return CODE_ERROR;
      }
    }
  }

答案 1 :(得分:0)

我运行的代码工作正常并且每次都要求输入,当我给出2或1个循环终止时。这是我运行的代码示例: -

   package testing;

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

public class Test123 {
    public static Scanner in = new Scanner(System.in);
    public static int CODE_ERROR = -6;

    public static int getInt(){
        try{
            String in1 = in.next();
             return Integer.parseInt(in1);
            //return in.nextInt(); <-- This is leading to error
        } catch(Exception e){
            return CODE_ERROR;
        }
}

    public static void main(String[] args) {
        int input;

        while((input = Test123.getInt()) != 1 && input != 2){
            if(input == Test123.CODE_ERROR)
                System.out.print("Input must be a number");

            System.out.println("\nWrong number: "+input+" Please try again.");


            //input = Test123.getInt();
        }
    }

}

我不明白你为什么面临问题?