【问题标题】:While loop repeating unexpectedly [Java]While 循环意外重复 [Java]
【发布时间】:2018-06-20 09:29:59
【问题描述】:

我目前正在关注一本关于 java 编程的书,我尝试做一个自学问题,要求制作一个程序来计算你按空格键的次数以及你必须点击“。”停止 while 循环。但是,循环似乎想要循环 3 次,而不是要求在一次之后再次输入密钥。这是代码

public class KeySelfTest {
public static void main(String args[]) throws java.io.IOException{
    char input;
    int space = 0;

    input = 'q';

    while (input != '.'){
        System.out.println("Enter a key");
        input = (char) System.in.read();
        if (input == ' '){
            space++;
        }
        else{
            System.out.println("Enter a period to stop");
        }

    }
    System.out.println("You used the spacebar key " + space + " times");    
}
}

我还想知道在实际循环之前我可以使用什么来初始化输入变量,而不是仅仅将其默认为像 q 这样的随机字母。感谢您的帮助。

【问题讨论】:

    标签: java while-loop


    【解决方案1】:

    这实际上是使用 do-while 循环的最佳时机。

    do {
        input = System.in.read();
        ...
    } while (input != '.');
    

    【讨论】:

      【解决方案2】:

      您可以在一个语句中分配和测试,例如

      char input;
      int space = 0;
      
      while ((input = (char) System.in.read()) != '.') {
          System.out.println("Enter a key");
          if (input == ' ') {
              space++;
          } else {
              System.out.println("Enter a period to stop");
          }
      }
      System.out.println("You used the spacebar key " + space + " times");
      

      【讨论】:

        猜你喜欢
        • 2021-01-03
        • 1970-01-01
        • 2019-04-13
        • 1970-01-01
        • 2023-04-01
        • 1970-01-01
        • 2015-08-06
        • 1970-01-01
        • 2019-02-19
        相关资源
        最近更新 更多