【问题标题】:How do I prompt a user until they enter a valid integer?在用户输入有效整数之前如何提示他们?
【发布时间】:2013-07-21 15:28:41
【问题描述】:

有效的整数是一个字母。我不知道让它检查字符串的命令,也不知道在哪里可以找到它。任何帮助将不胜感激。

import java.util.Scanner;

public class Stringtest{

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

    int test = 10;

    while (test>0){
    System.out.println("Input the maximum temperature.");
    String maxTemp = input.nextLine();
    System.out.println("Input the minimum temperature.");
    String minTemp = input.nextLine();
    }
}
}

【问题讨论】:

标签: java integer java.util.scanner


【解决方案1】:

使用nextInt() 获取下一个整数值。 如果用户键入非整数值,您应该尝试/捕获它。

这是一个例子:

Scanner input = new Scanner(System.in);
// infinite loop
while (true){
        System.out.println("Input the maximum temperature.");
        try {
            int maxTemp = input.nextInt();
            // TODO whatever you need to do with max temp
        }
        catch (Throwable t) {
            // TODO handle better
            t.printStackTrace();
            break;
        }
        System.out.println("Input the minimum temperature.");
        try {
            int minTemp = input.nextInt();
            // TODO whatever you need to do with min temp
        }
        catch (Throwable t) {
            // TODO handle better
            t.printStackTrace();
            break;
        }
}

【讨论】:

  • Mena,查看 OP 的最新问题。看来您不是在教他学习 Java,而是在教他乞求代码。
  • @HovercraftFullOfEels 现在感觉有点内疚;(不过,还是有一些工具可以规范/调节社区...
【解决方案2】:

只需使用input.nextInt(),然后对无效的 int 值进行简单的 try-catch。

您也不应该尝试将温度指数保存为Strings

【讨论】:

    【解决方案3】:

    你应该使用Integer.parseInt,即用户可以输入任何字符串,然后你可以使用这个api检查它是否是一个整数,如果它不是整数你会得到一个异常,然后你可以从用户那里输入另一个条目。查看以下链接了解使用情况。

    http://www.tutorialspoint.com/java/number_parseint.htm

    【讨论】:

      【解决方案4】:
      try{
       int num = Integer.parseInt(str);
       // is an integer!
       } catch (NumberFormatException e) {
       // not an integer!
       }
      

      【讨论】:

      • 最好使用Scanner#hasNextInt()Scanner#nextInt()
      【解决方案5】:

      也许你可以这样做:

      Scanner scanner = new Scanner(System.in); 
      int number;
      do {
          System.out.println("Please enter a positive number: ");
          while (!scanner.hasNextInt()) {
              String input = scanner.next();
              System.out.printf("\"%s\" is not a valid number.\n", input);
          }
          number = scanner.nextInt();
      } while (number < 0);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-05-10
        • 2019-06-20
        • 2019-03-20
        • 1970-01-01
        • 1970-01-01
        • 2020-09-26
        • 2011-09-17
        相关资源
        最近更新 更多