简体   繁体   English

java的while循环错误? 附加输出代码有什么问题?

[英]java while loop error? additional outputs what is the wrong with the code?

class demoWhile{        
public static void main(String args[])
    throws java.io.IOException{
        char ch = (char)System.in.read();
        while(ch!='w'){
            System.out.println("Hi"+ch);
            ch = (char)System.in.read();
        }
    }
}

-first I gave the input a 'r' and expected output was "Hir" then input option but instead received output was Hir, Hi, Hi then the input option. -首先,我给输入一个“ r”,预期的输出是“ Hir”,然后是输入选项,但是收到的输出是Hir,Hi,Hi,然后是输入选项。 why it shows two additional Hi, Hi? 为什么显示两个额外的嗨,嗨?

I suspect that you run this on a windows machine and pressed Enter after the 'r'. 我怀疑您是在Windows计算机上运行此程序,并在“ r”后按Enter。 If that's not the case, ignore this answer. 如果不是这种情况,请忽略此答案。

The enter is understood as a linebreak, which consist of the two bytes 0D 0A on windows. 输入被理解为换行符,由Windows上的两个字节0D 0A组成。 In String literals these are usually expressed as "\\r\\n" . 在字符串文字中,这些通常表示为"\\r\\n"

That causes three characters to be read: 'r', '\\r' (char 13) and '\\n' (char 10). 这将导致读取三个字符:“ r”,“ \\ r”(字符13)和“ \\ n”(字符10)。

Your code processes them individually, so the output is 您的代码分别处理它们,因此输出为

Hir
Hi\r
Hi\n

But the \\r and \\n dont get displayed since they only have an effect (on windows) when you combine them. 但是\\ r和\\ n不会显示,因为当您组合它们时,它们仅在Windows上起作用。

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

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