Print in new line, java
JavaPrintingNew OperatorPrintlnJava Problem Overview
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?
Java Solutions
Solution 1 - Java
String newLine = System.getProperty("line.separator");//This will retrieve line separator dependent on OS.
System.out.println("line 1" + newLine + "line2");
Solution 2 - Java
System.out.println("hello"+"\n"+"world");
Solution 3 - Java
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 it's perfect for the console.
If you are printing to a file, then it depends.
Solution 4 - Java
It does create a new line. Try:
System.out.println("---\n###");
Solution 5 - Java
You should use the built in line separator. The advantage is that you don't have to concern what system you code is running on, it will just work.
Since Java 1.7
System.lineSeparator()
Pre Java 1.7
System.getProperty("line.separator")
Solution 6 - Java
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.
Solution 7 - Java
\n
creates a new line in Java. Don't use spaces before or after \n
.
Example: printing It creates\na new line
outputs
> It creates
> a new line.
Solution 8 - Java
Since you are on Windows, instead of \n use \r\n (carriage return + line feed).
Solution 9 - Java
//Case1:
System.out.println(" 1 2 3 4 5 6 7 8 9" + "\n" + "----------------------------");
//Case2:
System.out.printf(" 1 2 3 4 5 6 7 8 9" + "\n" + "----------------------------");
//Case3:
System.out.print(" 1 2 3 4 5 6 7 8 9" + "\n" + "----------------------------");
Solution 10 - Java
/n
and /r
usage depends on the platform (Window, Mac, Linux) which you are using.
But there are some platform independent separators too:
-
System.lineSeparator()
-
System.getProperty("line.separator")
Solution 11 - Java
"\n" this is the simple method to separate the continuous String
Solution 12 - Java
System.out.print(values[i] + " ");
//in one number be printed