ユーザーからの入力を検証しようとしています。ユーザーは Y 座標に (AJ) の間の文字を入力し、x 座標には (1-9) の間の数字を入力します。y 座標は検証できますが、x 座標の検証に問題があります。ユーザーが1から9までの数字以外の何かを入力すると、ユーザーに有効な入力を求め続けます。
do {
// inner loop checks and validates user input
do {
System.out.println("Enter X Co-Ord (A-J), or Q to QUIT");
letter = input.next().toUpperCase(); // upper case this for
// comparison
if (letter.equals("Q"))
break; // if user enters Q then quit
String temp = "ABCDEFGHIJ";
while (temp.indexOf(letter) == -1) {
validString = false;
System.out.println("Please enter a valid input");
letter = input.next().toUpperCase();
col = temp.indexOf(letter);
}
if (temp.indexOf(letter) != -1) {
validString = true;
col = temp.indexOf(letter);
}
try {
System.out.println("Enter Y Co-Ord (0-9)");
row = input.nextInt();
} catch (InputMismatchException exception) {
validInt = false;
System.out.println("Please enter a number between 1 -9");
}
catch (Exception exception) {
exception.printStackTrace();
}
valuesOK = false; // only set valuesOK when the two others are
// true
if (validString && validInt) {
valuesOK = true;
}
} while (!valuesOK); // end inner Do loop
出力は次のとおりです。
X Co-Ord (AJ) または Q を入力して終了します
d
Y 座標を入力してください (0-9)
時間
1 ~ 9 の数字を入力してください
X Co-Ord (AJ) または Q を入力して終了します
Y 座標を入力してください (0-9)