Question

I have a paragraph which has been indented already. for example

Hello:
     Hi every body

Now I want to print this in Java. using System.out.println I have to put this function in each line. How can I do it like when you use print in python that you just put a " around it and it's already ready.

Was it helpful?

Solution 2

You have got one String.format method, that returns a formatted string: -

String str = String.format("%s%n%20s", "Hello", "Hi everyone!");
System.out.println(str);

%n in string formatting is used to print a newline character.

%20s will right indent the string, and will take 20 charater space.


If you want to print the formatted string, rather than storing it, you can use System.out.format: -

System.out.format("%s%n%20s", "Hello", "Hi everyone!");

OTHER TIPS

Formatting the string like this is one way:

"Hello:\n\tHi every body"

You can use special characters like \n for new line.

System.out.println("Hello:\n     Hi everybody");

Sure, you just use newline and tab escape sequences - \t and \n

Here's a simple example:

//Note: Text content in the code blocks is automatically word-wrapped
import java.io.*;  

class Tabs {  
  public static void main(String[] args) {  
    try {  
      String t = "\t\t";  
      PrintStream ps = new PrintStream("tabs.txt");  
      ps.print("A" + t + "B");  
      ps.print("C\t\tD");  
    } catch(Exception e) {  
      System.err.println(e);  
    }  
  }  
}  

source

Also see - Printing with "\t" (tabs) does not result in aligned columns

Play with it, you'll figure it out

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top