gpt4 book ai didi

java - 同时报告多个错误

转载 作者:太空宇宙 更新时间:2023-11-04 11:01:07 25 4
gpt4 key购买 nike

((不删除,以便将来可以使用)) 适合任何需要使用 if 语句打印出多个错误的字符串的帮助的人。不要忘记导入 Scanner 和 regex.Pattern。编辑以减少困惑并删除我使用的具体信息。

public static boolean checkPass(String s) {
Pattern p = Pattern.compile("[bB]{2}[0-9]{4};
return p.matcher(s).find();
}

public static void main(String[] args) {

String inputMessage = "Enter a code to validate: ";
String userInput = " ";
Scanner input = new Scanner(System.in);

System.out.println(inputMessage);
userInput = input.nextLine();

while (userInput.length() != 6 || !checkPass(userInput)) {

if (userInput.charAt(0)!= 'b')
System.out.println("First Character is not a b or a B");
if (userInput.charAt(1)!= 'b')
System.out.println("Second character is not a b or B");
if (!Character.isDigit(userInput.charAt(2)))
System.out.println("Third character is not digit");

System.out.println("Code: " + userInput + " is not valid");
userInput = input.nextLine();
}



System.out.println("code: " + userInput + " is valid");



}

}

最佳答案

if (userInput.charAt(2) != 0-9)... 不会检查 userInput 位置 2 处的字符是否不在 09 范围内。它检查字符是否不等于-9。 char永远不会是负数,因此任何字符(甚至字母和标点符号)都会通过此测试。

您想要的是:

if (userInput.charAt(2) < '0' || userInput.charAt(2) > '9') 
...

if (!Character.isDigit(userInput.charAt(2)))
...

关于java - 同时报告多个错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46881404/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com