Win a copy of hapi.js in Action this week in the HTML, CSS and JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

formatted toString with no spacing

 
Jeremy Doseck
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I have this code >
in Students class:


in SimpleDB class:


in main class:




the output text is not aligned to the right... does anyone have some ideas how to do it?
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 35524
402
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jeremy,
Welcome to CodeRanch!

Take a look at the System.out.printf method. It lets you specify the desired length/padding/formatting.
 
Jeremy Doseck
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
it doesn't work..I tried this code:


my goal is to get rid of brackets and commas that toString() method produces, AND to align all lines to the right..
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 35524
402
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh! Then you want to loop through the ArrayList so only one item is printed per line. That will get rid of the brackets and commas leaving printf to do the alignment.
 
Carey Brown
Bartender
Posts: 2125
26
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

You shouldn't use "\n", especially in a printf() where you should use "%n" instead.

In printf, "%s" will print a String using the same number of characters as the String contains.

When you say "justify right" you'd want to pad the string like "%30s". This will allocate 30 characters for the String and display it right justified. To display it left justified use "%-30s". Note that if your string is more than 30 characters it will be printed as wide as nessesary to print all characters in your string, thus throwing off your column alignment.

You can leave spaces or other text between fields in the format string:
 
Jeremy Doseck
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
now it works fine ! thanks.

 
Junilu Lacar
Sheriff
Posts: 9338
96
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you tried that using longer names? Like "Bartholomew"? The \t is only going to be consistent if your names are all under 8 characters. Longer names will cause the | and the email address to get pushed out to the next tab stop. You should try short names, too, like Stu, Tim, and Al. Tab stops are typically in multiples of 4 or 8, I can't be sure but it's one of those.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!