我正在编写一个程序,它是一个游戏,你必须猜测计算机生成的随机 4 位整数。我在输入验证时遇到问题 - 更具体地说,是我的 isDigit() 方法,该方法旨在确保来自 userGuess 的所有输入都是数字 0 - 9:
private static boolean isDigit(char indexPos) { // verifies if the input char is a digit 0-9 or not
if(indexPos == 0 || indexPos == 1 || indexPos == 2 || indexPos == 3 || indexPos == 4 || indexPos == 5 || indexPos == 6 || indexPos == 7 || indexPos == 8 || indexPos == 9) {
return true;
}
else {
return false;
}
}
如果我硬编码之类的东西
isDigit(1)
它评估为真,但如果我插入变量,它会返回假。主要是,这会返回 false,即使 userGuess 的所有索引位置都是数字 0-9:
isDigit(userGuess.charAt(i)) // returns false even when index pos i is [0-9]
对于为什么会发生这种情况,我完全感到困惑和困惑。对于上下文,这是验证的整个 if 和 for 循环情况:
numGuess++;
System.out.print("Guess " + numGuess + ": ");
userGuess = kbd.nextLine();
System.out.println("DEBUG: userGuess.length() : " + userGuess.length());
// validate that the input is a valid input (a 4 digit natural number, incl 0000)
if(userGuess.length() < 4 || userGuess.length() >= 5){
System.out.println("Please enter a valid input, which is a 4 digit natural number (postive integer, including 0000).");
}
else if(userGuess.length() == 4) {
for(int i = 0; i <= 3; i++) {
if(isDigit(userGuess.charAt(i)) == true) {
validateCount++;
}
}
我也有,我认为是同样的问题,验证 userGuess.length() == 4。如果我在控制台上输出 userGuess.legnth(),它提供了正确的数字,当 == 4 时,这个if 循环不运行,即使满足条件:
if (userGuess.length() < 4 || userGuess.length() >= 5) {
System.out.println("Please enter a valid input, which is a 4 digit natural number (postive integer, including 0000).");
} else if (userGuess.length() == 4) { // avoid out of bounds errors for inputs less than 4 digits
for (int i = 0; i <= 3; i++) { // userGuess will never have an index above 3, as it is a 4 digit number
if (isDigit(userGuess.charAt(i)) == true && userGuess.length() == 4) { // verify that the userInput is a 4 digit integer
validateCount++;
}