Text Alignment/Justification

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • tachyon1984
    New Member
    • Jan 2008
    • 2

    #1

    Text Alignment/Justification

    Need some help in trying to align text using System.out.prin tln().

    An example of the problem is shown here:
    Code:
    	table_loc		lab		addr
    	142			GB		19
    	143			LH		25
    	632			RRUYLLLL		1AA
    The code:
    Code:
    System.out.println("\ttable_location\t\tlabel\t\taddr");
    		
    		for(int i = 0; i < hSize; i++)
    		{
    			if(!(Array[i].getLab().equals(empty)))
    				System.out.println("\t"+i+"\t\t\t"+Array[i].getLab()+"\t\t"+Array[i].getNum());
    		}
    As you can see I have attempted to use tabs.
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    Originally posted by tachyon1984
    Need some help in trying to align text using System.out.prin tln().

    An example of the problem is shown here:
    Code:
    	table_loc		lab		addr
    	142			GB		19
    	143			LH		25
    	632			RRUYLLLL		1AA
    The code:
    Code:
    System.out.println("\ttable_location\t\tlabel\t\taddr");
    		
    		for(int i = 0; i < hSize; i++)
    		{
    			if(!(Array[i].getLab().equals(empty)))
    				System.out.println("\t"+i+"\t\t\t"+Array[i].getLab()+"\t\t"+Array[i].getNum());
    		}
    As you can see I have attempted to use tabs.
    1.) Welcome to TSDN. Hope you'll have a great time here.
    2.) Thanks for using code tags. Next time just add =java in your opening code tag so it looks like [CODE=java]. That will enable the syntax highlighting.
    3.) Aligning with println can be tricky. Unfortunately, the best way to master it is to try as many examples as possible. Check your tabs and make sure you put the same number for your heading as you put for your rows.

    Comment

    • tachyon1984
      New Member
      • Jan 2008
      • 2

      #3
      Okay, I got it now. All I did was create a for loop to create a string of spaces based on the length of a label.

      Comment

      • BigDaddyLH
        Recognized Expert Top Contributor
        • Dec 2007
        • 1216

        #4
        A simpler solution is to use the format method. Demo:
        [CODE=Java]public class FormatExample {
        public static void main(String[] args) {
        String[] text = {"a", "bb", "ccc", "dddd"};
        int[] data = {1, 22, 333, 4444};

        for(int i=0; i<data.length; ++i) {
        String s = text[i];
        int x = data[i];
        System.out.form at("|%8s|%8d|%1 $-8s|%2$-8d|%n", s, x);
        }
        }
        }[/CODE]
        output:
        [HTML]
        | a| 1|a |1 |
        | bb| 22|bb |22 |
        | ccc| 333|ccc |333 |
        | dddd| 4444|dddd |4444 |
        [/HTML]
        Note that format methods were added in 1.5, so you need a fairly recent version.

        Comment

        Working...