【问题标题】:Make a code repeat loop if user input a non-numeric character?如果用户输入非数字字符,请进行代码重复循环?
【发布时间】:2014-10-17 06:15:56
【问题描述】:

目标:

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

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循环?也没有扫描仪方法。

【问题讨论】:

  • Character.isDigit();将检查单个字符数。

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


【解决方案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

【讨论】:

    【解决方案2】:

    试试这个

    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());
    

    【讨论】:

      【解决方案3】:

      这个怎么样

          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");
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-03
        • 2023-03-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多