Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question on System.out.print(...)

 
xin wen
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Anyone know if there is a way to do this?
When I use System.out.print(...), there are three columns and twenty rows, but the data is in different size, so when I displayed them, they can not be at the same columns, for example:
abcde adddddd yyyyyyyy
as jk rt
What I want is to adjust jk in adddddd column, and rt is in yyyyyyy column, so I wander if you know how to do it in java?
Thanks so much!
 
Pradeep bhatt
Ranch Hand
Posts: 8927
Firefox Browser Java Spring
 
Jason Kretzer
Ranch Hand
Posts: 280
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One way, maybe not the best way is to pad with spaces. For example, lets say each column is 20 spaces wide. And you have to display the following row
String[] s1 = {"asdf", "fdsa", "jklh", "hlkj"};
each of which is its own String. You could use a StringBuffer and pad as so

this should give you a rough idea on how it can be done.
Best Regards,
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Going to std out for screen display, you need to pad the short strings with spaces to match the length of the longest strings. You might have to loop through your data first to find the longest string in column 1 and then pad every row to that length. Or you might know a reasonable maximum length ahead of time.
I made myself a String utility class with static methods inspired by the Rexx language, so I'd do something like:

left and right methods pad or truncate to a given length. You can optionally tell them what pad character to use.
Probably seems like more work than you were hoping for? Hope it helps!
 
xin wen
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks all for replying and helps!
I will try to see if I can make it working!
 
chi Lin
Ranch Hand
Posts: 348
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
some otehr convenient methods regarding alignment I saw at Javaranch
(sorry, forgot who the author is )
 
Sainudheen Mydeen
Ranch Hand
Posts: 218
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Using StringBuffer will be a better approach.
-Sainudheen
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic