java - 如何修复 java 中 while 循环的条件

标签 java string while-loop infinite-loop logical-operators

我的代码很简单;检查字符串中有多少数字、小写字母、大写字母和特殊字符,但必须至少有一个;

我认为我的 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/

相关文章:

java - 将数字转换为字母的程序

java - 对应的then子句没有正常完成

bash - 不会记住在 while 循环内修改的变量

c - lowlevellock 和无限 While 循环

java - cURL命令上传文件不上传文件

java - 如何在 JavaFX 中为提示文本添加换行符?

mysql - 如何将数据与选定数据分开

javascript - 如何将 JavaScript 代码转换为一个大的 Java 字符串

string - 获取字符串值形式的 VB6 变量名称

java - 如何在for循环中设置限制?