我正在尝试验证来自用户的输入。用户在 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)
H
请输入一个介于 1 -9 之间的数字
输入 X Co-Ord (AJ),或 Q 退出
输入 Y 坐标 (0-9)