java - 为什么我的 while 循环导致 java 控制台不出现?

标签 java

我想要的循环是让程序循环直到满足接受的条件。我尝试切换运算符以获得我想要的循环。我确信这是满足我的条件的正确代码,但这会导致我的 java 控制台根本不出现!

有人可以解释一下我做错了什么吗?

while (total % 5 != 0) {


        System.out.println("Enter 3 a-z characters");

        Scanner scan = new Scanner(System.in);

        Pattern pattern = Pattern.compile("^[a-zA-Z]$");


        for (int i = 0; i < 3; i++) {
            String input = scan.nextLine();
            while (!pattern.matcher(input).matches()) {
                System.out.println("Incorrect");
                input = scan.nextLine();
            }
            int letter = input.charAt(0);
            if (letter >= 97 && letter <= 122) {
                total += letter - 96;
            } else if (letter >= 65 && letter <= 90) {
                total += letter + 36;
            }
        }

          if   (total % 5 == 0) {
              System.out.println("accepted");
          } else  {
              System.out.println("not accepted");

              scan.close();
          }
      }
  }
}

最佳答案

由于total的初始值为0,因此您永远不会进入while循环。将 total 初始化为不是 5 倍数的数字。 总计=1

这只会解决您看不到输入控制台的问题。

为了解决这个问题,我将使用另一个变量来跟踪是否可以打破 while 循环。

public static void main(String[] args) {
    boolean accepted = false;
    Scanner scan = new Scanner(System.in);
    Pattern pattern = Pattern.compile("^[a-zA-Z]$");
    int total = 0;
    while (!accepted) {
        System.out.println("Enter 3 a-z characters");
        for (int i = 0; i < 3; i++) {
            String input = scan.next();
            while (!pattern.matcher(input).matches()) {
                System.out.println("Incorrect");
                input = scan.nextLine();
            }
            int letter = input.charAt(0);
            if (letter >= 97 && letter <= 122) {
                total += letter - 96;
            } else if (letter >= 65 && letter <= 90) {
                total += letter + 36;
            }
        }

        if (total % 5 == 0) {
            System.out.println("accepted");
            accepted = true;
            scan.close();
        } else {
            System.out.println("not accepted");
            total = 0;
        }
    }
}

关于java - 为什么我的 while 循环导致 java 控制台不出现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59492328/

相关文章:

java - 单选按钮无法正确显示

java - fatal error VS 异常

java - 性能静态初始化

java - 使用 Java 的桌面数据库应用程序

c# - 在 .pgm 图像中提取颜色位的最快方法?

java - 致命异常 : java. lang.NoSuchMethodError:没有虚拟方法 callEngineReleaseConnection(Lcom/squareup/okhttp/Call;)

java - <xs :any> inside an <xs:all> XSD 1. 0 解决方法?

带有 JPanel 的 Java 布局管理器

java - 如何防止用户修改其他用户的数据?

java - JPA 序列生成器不工作