views:

85

answers:

5

Hi,

I have following code :

    System.out.println(" | 1  2  3  4  5  6  7  8  9");
    System.out.println("----------------------------");
    System.out.println("");

I use println to create a new line. Is it possible to do the same using \n or \r? I tried to add \n to the second println statment and continue printing with the print method but \n does not create a new line.

any ideas?

A: 

Can you use \r\n together to achieve this.

sushil bharwani
It's `\r\n`, not `\n\r`.
BoltClock
that would be \r\n.
spender
Thanks for correction i edited my answer
sushil bharwani
Regardless, it's a platform-specific answer. Use the line.separator property mentioned in another post.
Andy Thomas-Cramer
+3  A: 

It does create a new line. Try:

System.out.println("---\n###");
brunodecarvalho
In the past, the Apple Mac requirse lines to be separated by '\r', So its better to write system independent code , check my solution
org.life.java
He's talking about "new line". Had he requested "new line + carriage return" I'd pointed him to \r\n :) If we're going to be picky, then I'd suggest using a StringBuilder rather than concatenating strings.
brunodecarvalho
For `"line 1" + newLine + "line2"` using a StringBuilder explicitly would be counter-productive. The compiler can optimize this by itself.
Thilo
+4  A: 

You might try adding \r\n instead of just \n. Depending on your operating system and how you are viewing the output, it might matter.

James Branigan
+1  A: 

Your best shot would be with

String.format("%n")

or

System.out.printf("%n");

It is supposed to print a newline character, depending on the current platform, so is perfect for the console. If you are printing to a file, then it depends.

vstoyanov
+5  A: 
    String newLine = System.getProperty("line.separator");//This will retrieve line separator dependent on OS.

    System.out.println("line 1" + newLine + "line2");
org.life.java