Java - New Line Character Issue

后端 未结 4 811
半阙折子戏
半阙折子戏 2021-01-28 01:50

I have a code like,

String str = \" \" ; 

while(  cond ) {

  str = str + \"\\n\" ;

}

Now, I don\'t know why at the time of printing, the out

相关标签:
4条回答
  • 2021-01-28 02:25

    Based on your sample, the only reason it would not show a new line character is that cond is never true and thus the while loop never runs...

    0 讨论(0)
  • 2021-01-28 02:28

    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 ;
    
    }
    
    0 讨论(0)
  • 2021-01-28 02:33

    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 :

    NEWLINE

    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

    0 讨论(0)
  • 2021-01-28 02:44

    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);
    
    0 讨论(0)
提交回复
热议问题