我的代码很简单;检查字符串中有多少数字、小写字母、大写字母和特殊字符,但必须至少有一个;
我认为我的 while 循环中条件的 AND 或 OR 有问题
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
String name = scn.nextLine();
checkPass(name);
}
public static void checkPass (String str){
int toul = str.length();
int normalLower=0;
int normalUpper=0;
int number=0;
int special=0;
while(normalLower==0 || normalUpper==0 || number==0 || special==0) {
for (int i = 0; i < toul; i++) {
String s = String.valueOf(str.charAt(i));
if (s.matches("^[a-z]*$")) {
normalLower++;
} else if (s.matches("^[A-Z]*$")) {
normalUpper++;
} else if (s.matches("^[0-9]*$")) {
number++;
} else {
special++;
}
}
}
System.out.println("normalupper " + normalUpper);
System.out.println("normallower " + normalLower );
System.out.println("number" + number);
System.out.println("special " + special);
}
我希望它在缺少 char 类型时请求字符串,但它很简单不会
最佳答案
尝试从 checkPass
方法返回 boolean
状态并在你的 main
方法中放置一个 while 循环,状态将是你的条件正在检查。
如果输入的字符串通过验证,您可以通过这种方式打破 while 循环,否则循环将继续询问有效输入 String
:
public static void main(String[] args) throws Exception {
Scanner scn = new Scanner(System.in);
String name = scn.nextLine();
while(checkPass(name)){
name = scn.nextLine();
}
}
// If the boolean retuned from this method is false it will break the while loop in main
public static boolean checkPass(String str) {
int toul = str.length();
int normalLower = 0;
int normalUpper = 0;
int number = 0;
int special = 0;
for (int i = 0; i < toul; i++) {
String s = String.valueOf(str.charAt(i));
if (s.matches("^[a-z]*$")) {
normalLower++;
} else if (s.matches("^[A-Z]*$")) {
normalUpper++;
} else if (s.matches("^[0-9]*$")) {
number++;
} else {
special++;
}
}
System.out.println("normalupper " + normalUpper);
System.out.println("normallower " + normalLower);
System.out.println("number" + number);
System.out.println("special " + special);
return normalLower == 0 || normalUpper == 0 || number == 0 || special == 0;
}
关于java - 如何修复 java 中 while 循环的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57980507/