0

my code uses a for loop like so:

for(int i=0; i<100; i++)
{
  System.out.print(number + "\t");
}

Of course my for loop is more complicated than that but i just typed that in for demonstration purposes. I am using "\t" for alignment in my table but it makes the columns print too far apart. my current output is:

1     2     3     4 
--    --    --    --        
1     1     1     4                         
0     2     2     2                 
0     0     3     3

how can i reduce the space that tab "\t" makes? my other question is how can i split the line at 80 characters so that my output does not exceed the page width?

Chalupa
  • 367
  • 1
  • 5
  • 20
  • 4
    There is a format printer API available in Java since 1.5 to format output using certain "standard" sequences. Have a look at http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html – ring bearer Jun 20 '15 at 17:39
  • If you are thinking about cursor positioning and printing at any X,Y position , then use Laterna https://code.google.com/p/lanterna/ – Dickens A S Jun 20 '15 at 17:42
  • 3
    Note that the number of space that a tab character is represented as is a function purely of your console window or file editor. Not really a Java problem ... – dhke Jun 20 '15 at 17:42

1 Answers1

1

A better idea would be to use System.out.format (with the appropriate format applied) than System.out.println. See the Javadoc and this nice cheatsheet.

public class Misc {
  public static void main(String args[]){
      String format = "|%1$-10s|%2$-10s|%3$-20s|\n";
      System.out.format(format, "FirstName", "Init.", "LastName");
      System.out.format(format, "Dick", "", "Smith");
      System.out.format(format, "John", "D", "Doe");

      String ex[] = { "John", "F.", "Kennedy" };

      System.out.format(String.format(format, (Object[])ex));
  }
}

output :

|FirstName |Init.     |LastName            |
|Dick      |          |Smith               |
|John      |D         |Doe                 |
|John      |F.        |Kennedy             |
RealHowTo
  • 34,977
  • 11
  • 70
  • 85
  • can you please explain what the numbers in %1$-10s represent? does this allow me to split the line at 80 characters? – Chalupa Jun 20 '15 at 17:55
  • also how can i use this when i have a large number of strings? like 100. i can't type each one individually – Chalupa Jun 20 '15 at 17:57
  • @Chalupa %1$ is a place to match the first parameter as a string, -10s format the string left-justified with a width of 10 spaces. Read the 2 given links to learn how it works! As for the second question, well ... you can have an array or file with your data and loop through them elements to print line by line. – RealHowTo Jun 20 '15 at 18:07