简体   繁体   English

Java For循环中的逻辑错误

[英]Logic Error in Java For-loop

I am trying to make the loop continue to execute here until the user types the letter S at the keyboard. 我试图让循环继续执行,直到用户在键盘上键入字母S. It seems to be giving three outputs instead of one for each iteration. 它似乎是为每次迭代提供三个输出而不是一个输出。 What am I doing wrong here; 我在这做错了什么;

// Loop until an S is typed

public class ForTest {

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

        int i;

        System.out.println("Type S to stop.");

        for(i = 0; (char) System.in.read() != 'S'; i++) 
//          System.out.println("print");
            System.out.println("Pass # " + i);
//          System.out.println("print");


    }

}

Output coming up is if I press 'a': 如果我按'a',输出就会出现:

Type S to stop.
a
Pass # 0
Pass # 1
Pass # 2

The InputStream.read method block until the end of input which is on a Windows OS the control characters CR LF (\\r\\n). InputStream.read方法阻塞直到输入结束,这是在Windows操作系统上控制字符CR LF(\\ r \\ n)。

This explains why you get 3 characters as a result. 这就解释了为什么你得到3个字符的结果。

See for yourself : 你自己看 :

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

    int i;

    System.out.println("Type S to stop.");

    char c = (char) 0;
    for (i = 0; c != 'S'; i++) {
        c = (char) System.in.read();
        System.out.println("Pass # " + i);
        System.out.println("char intValue : " + (int) c);
    }
}

Suggested read : Java: How to get input from System.console() 建议阅读: Java:如何从System.console()获取输入

System.in will use BufferedInputSteam to read the input from console bit by bit (including the line break, etc). System.in将使用BufferedInputSteam逐位读取控制台的输入(包括换行符等)。 In Mac system, I get 2 bits whenever i gave a single digit input. 在Mac系统中,每当我输入一位数时,我得到2位。

Use Scanner and read all the bytes and convert as String. 使用扫描程序并读取所有字节并转换为字符串。

I suggest you to avoid reading input in that way, use Scanner instead. 我建议你避免以这种方式阅读输入,而是使用Scanner You can reach your goal with this code: 您可以使用以下代码实现目标:

    int i = 0;
    Scanner scan = new Scanner(System.in);
    System.out.println("Type S to stop.");
    while( !scan.next().equals("S")) {
        i++;
        System.out.println("Pass # "+i);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM