简体   繁体   中英

Java - New Line Character Issue

I have a code like,

String str = " " ; 

while(  cond ) {

  str = str + "\n" ;

}

Now, I don't know why at the time of printing, the output string is not printing the newline character. However, when I add any other character like ( str = str + "c"), it is printing properly. Can anybody help me, how to solve this problem and why this happening ?

The newline character is considered a control character , which doesn't print a special character to the screen by default.

As an example, try this:

String str = "Hi";
while (cond) {
    str += "\n"; // Syntactically equivalent to your code
}
str += "Bye";
System.out.println(str);

Looks like you are trying to run the above code on Windows. Well the line separator or new line is different on Windows ( '\\r\\n' ) and Unix flavors ('\\n').

So, instead of hard coding and using '\\n' as new line. Try getting new line from the system like:

String newLine = System.getProperty("line.separator");
String str = " " ; 

while(  cond ) {

  str = str + newLine ;

}

If you really want \\n, to get printed, do it like this.

String first = "C:/Mine/Java" + "\\n";
System.out.println(first);

OUTPUT is as follows :

新队

For a good reference as to why is this happening, visit JAVA Tutorials

As referred in that TUTORIAL : A character preceded by a backslash is an escape sequence, and has a special meaning to the compiler. When an escape sequence is encountered in a print statement, the compiler interprets it accordingly

Hope this might help.

Regards

根据您的示例,它不会显示换行符的唯一原因是cond永远不会为真,因此 while 循环永远不会运行...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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