-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

多分あなたはこのようなことをすることができます:

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 に答える
0

つまり、ユーザーは任意の文字列を入力でき、この API を使用Integer.parseIntして整数かどうかを確認できます。整数でない場合は例外が発生し、ユーザーから別のエントリを取得できます。使い方は以下のリンクをご確認ください。

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 に答える