如何在用户输入有效整数之前提示用户?

时间:2013-07-21 15:28:42

标签: java integer java.util.scanner

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

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

5 个答案:

答案 0 :(得分:2)

使用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;
        }
}

答案 1 :(得分:1)

只需使用input.nextInt(),然后使用简单的try-catch来获取无效的int值。

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

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

try{
 int num = Integer.parseInt(str);
 // is an integer!
 } catch (NumberFormatException e) {
 // not an integer!
 }

答案 4 :(得分:0)

也许你可以这样做:

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