Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Formatting concatenated string objects

 
C Bick
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to return a string made up of several different concatenated variables of multiple types to a different class. This part is working just fine, the problem is I want the data to show up in neat organized columns in the output from the second program.

The first column of the output is made up of 4 digit numbers...no problem there - I can line that up every time with no problem. The second column is what is causing me problems. It can be between 1 and 20 characters (I set a maximum length of 20 characters of returned input from user's entry) so it is impossible to use a fixed number of spaces to line it up (ie... " " (4 spaces)). Is there a way to set up a variable number of spaces to be displayed, similar to System.out.Printf()'s functionality?

What would be perfect would be if I could set up a statement like -

20 - stringlength = number of spaces to display


Here is the relevant code I have so far with my current (sad) absolutely specified number of spaces...

[edit]Add code tags to retrieve spacing. CR[/edit]
[ December 04, 2008: Message edited by: Campbell Ritchie ]
 
C Bick
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
looks like the extra spaces between the quotes got taken out, but suffice it to say that there were different numbers between each set of quotes.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49776
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Somebody else had a similar problem yesterday. Here. I think the printf method and the % tags with widths will help.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49776
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by C Bick:
looks like the extra spaces between the quotes got taken out, but suffice it to say that there were different numbers between each set of quotes.


You ought to have used the code button; that would have preserved the spaces.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49776
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have edited your post to add code tags, and your spacing has reappeared. You do realise you can set widths and left-justified or right-justified with the printf method?
You can also set up a for loop to count spaces and add them together, but I don't think much of that solution.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic