如果用户输入非数字字符,请进行代码重复循环?

时间:2014-10-17 06:15:57

标签: java loops if-statement while-loop numbers

目标:

如果用户输入非数字编号,请再次运行循环。 还有另一种(更有效的)编写数字输入的方法吗?

public static void user_input (){
   int input;
   input = fgetc (System.in);
   while (input != '\n'){
      System.out.println("Please enter a number: ");
      if (input == '0' == '1' ..... '9'){
          //Execute some code
      }
      else {
          System.out.println("Error Please Try Again");
          //Repeat While loop
      }
   }
}

修改

我需要while循环条件。简单地问,你如何重复while循环?也没有扫描仪方法。

3 个答案:

答案 0 :(得分:1)

使用next代替nextInt进行输入。放置try catch以使用parseInt方法解析输入。如果解析成功break the while loop,则为continue。试试这个:

public static void user_input() {
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.println("Enter a number.");
            String input = sc.next();
            int intInputValue = 0;
            try {
                intInputValue = Integer.parseInt(input);
                System.out.println("Correct input, exit");
                break;
            } catch (NumberFormatException ne) {
                System.out.println("Input is not a number, continue");
            }
        }
    }

<强>输出

Enter a number.
w
Input is not a number, continue
Enter a number.
3
Correct input, exit

答案 1 :(得分:0)

试试这个

System.out.println("Please enter a number: ");
Scanner userInput = new Scanner(System.in);

while(!userInput.hasNextInt()) {
    System.out.println("Invalid input. Please enter again");
    userInput = new Scanner(System.in);
}
System.out.println("Input is correct : " + userInput.nextInt());

答案 2 :(得分:0)

这个怎么样

    public static void processInput() {

    System.out.println("Enter only numeric: ");
    Scanner scannerInput;

    while (true) {
        scannerInput = new Scanner(System.in);

        if (scannerInput.hasNextInt()) {
            System.out.println("Entered numeric is " + scannerInput.nextInt());
            break;
        } else {
            System.out.println("Error Please Try Again");
        }
    }
}