-3

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

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

5 回答 5

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;
        }
}
于 2013-07-21T15:34:44.507 回答
1

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

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

于 2013-07-21T15:33:43.523 回答
0

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

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

于 2013-07-21T15:31:59.960 回答
0
try{
 int num = Integer.parseInt(str);
 // is an integer!
 } catch (NumberFormatException e) {
 // not an integer!
 }
于 2013-07-21T15:32:25.297 回答
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);
于 2013-07-21T15:43:37.133 回答