ユーザーの入力が正の整数であることを検証する簡単なプログラムを作成しようとしています。しかし、私はScanner.hasNextInt()メソッドを使用するときに問題に遭遇しています。入力に「5 6」のような整数が含まれている場合、私のプログラムは6 inを整数として読み込みます。しかし、私はそのようなステートメントを無効にして、ユーザーに整数値を入力する必要があることをユーザーに促します。したがって、プログラムは「整数値を入力してください:」と出力します。スキャナの入力が整数のみであることを確認してください
import java.util.Scanner;
public class InputValidation {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
// INPUT VALIDATION FOR INTEGERS AND POSITIVE NUMBERS
int input = 0;
boolean validationSuccessful = false;
System.out.print("Please enter the input: ");
do {
// validate that the input is an integer
if (in.hasNextInt() == true) {
input = in.nextInt();
} else {
System.out.print("Please enter an integer value: ");
in.next();
continue;
}
// validate that the input is positive
if (input < 0) {
System.out.print("Please print a POSITIVE integer: ");
continue;
} else {
validationSuccessful = true;
}
System.out.println("The input is: " + input);
} while (validationSuccessful == false);
}
}
編集:これは私のプログラムのように見えるものである
I)は、次の()nextLine(対の違いを理解しています。しかし、私の問題は、実際には整数だけである行と、整数を含む行の検証の側面です。あなたは
in.next();
を使用する場合にのみトークンつの単語を/読み込み
in.nextLine();
回線使用を破棄する
[Data Validation and Scanners in Java]の複製可能性があります(http://stackoverflow.com/questions/30770426/data-validation-and-scanners-in-java) – Andremoniy
nextLine()を使用したいのですか?単語を破棄するnext()の代わりに行全体を破棄するには? –
@PeterLawreyはい、整数だけでなく、行全体を破棄したいと思います。 –