我遇到了这段代码的问题,特别是while循环中的代码 .
public void mSetSafeCode() // Manually define safe passcode
{
int mIntPasscode;
String mStringPasscode;
Scanner sc = new Scanner(System.in);
System.out.print("Enter your desired numerical passcode (max 3 digits): ");
mStringPasscode = sc.nextLine();
while(mStringPasscode.matches("\\D+") || mStringPasscode.length() > 3 || mStringPasscode.length() < 3) // If input not digit or exceeds length
{
System.out.print("Error! You inputted an invalid passcode, try again: ");
mStringPasscode = sc.nextLine(); // Prints error, gets user to input again
}
mIntPasscode = Integer.parseInt(mStringPasscode); // If while is not met, parses input into an integer
System.out.println("You've set the numerical passcode to " + mIntPasscode); // Prints the passcode
}
我试图这样做,而扫描仪的用户输入包含不是数字的字符,以抛出错误 . 我相信我的正则表达式是正确的 \\D+ 但是如果我使用'f33'作为输入,例如,它使用或使用字符串长度是't caught in the while loop. I think this is because I' m,但是如果它包含一个字符,我希望它被while循环捕获(不是数字)或其长度是否大于/小于3 .
谢谢您的帮助!