【问题标题】:for loop iterated unexpectedlyfor 循环意外迭代
【发布时间】:2021-01-31 17:05:25
【问题描述】:

我是 Java 编程的新手,正在尝试自学该语言。我想创建一个在输入“s”时终止的程序,但让我感到困惑的是我的 for 循环在输入字母后迭代了两次?

我的代码:

public class Demo {
    public static void main(String[] args)
        throws java.io.IOException{

        int i;
        System.out.println("Press s to stop: ");
        for(i = 0; (char) System.in.read() != 's'; i++)
            {
                System.out.println("Pass #"+i);
  
            }

    }

我的结果:

我应该如何解决这个问题?

【问题讨论】:

    标签: for-loop user-input inputstream


    【解决方案1】:

    这是因为当您按下回车键时,\n 也会进入输入流。

    因此,一个迭代用于字母,另一个用于\n 字符。

    解决方案是:

    public class Demo {
        public static void main(String[] args)
            throws java.io.IOException{
    
            int i;
            System.out.println("Press s to stop: ");
            char c = System.in.read();
            for(i = 0;  c != 's'; i++)
                {
                    if(c == '\n') continue;
                    System.out.println("Pass #"+i);
                    c= System.in.read();
                }
    
        }
    

    【讨论】:

    • 有没有不读取缓冲区中的 '\n' 的方法?
    • 嗯,我不认为你可以这样做,但你可以检查 java.io.Console.flush() 或者你可以使用扫描仪作为另一个选项
    猜你喜欢
    • 2015-02-03
    • 1970-01-01
    • 2012-06-27
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多