Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

StringBuffer toString method

 
Jimmy Anderson
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
I am working through the Java Tutorial third edition and one of the exercises is to write a program that computes your initials from your full name and displays them. I set the app up to accept the full name from the command line. My thought was to first append the first letter of the string to a StringBuffer then iterate through the string and append the character after a blank space to the StringBuffer. The output only prints the first letter of the string though. After some experimentation it seems that when I use the toString method on the StringBuffer it removes the whitespaces so the loop never finds a blank space. Can any explain why this is and how can I get around it?
Thanks in advance!! Here's my code:
 
Jeff Bosch
Ranch Hand
Posts: 805
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, Jimmy -
Arguments are separated by whitespace, but the whitespace is not part of the argument. Running java Initials Jeffrey Scott Bosch produces the following elements of the args array:
args[0] = "Jeffrey"
args[1] = "Scott"
args[2] = "Bosch"
Concatentation would produce JeffreyScottBosch. You could append a space after adding the element if the element index is less than (args.length - 2):

Now you have a space appended after every name in the StringBuffer except the last name.

Note: I would also use a for loop instead of the while, but that's just my preference.

Regards,
Jeff
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why do you concatenate the arguments at all, just to separate them again?
 
Richard Teston
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
yeah, i agree with Ilja why not get every initial character with every elements of String in the command line arguments?
 
Jimmy Anderson
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your responses.
For some reason I was thinking that the command line was returning one String object instead of an array with three String elements. Your responses made me realize my mistake and I have revised the program. It works fine now. Thanks again for your help.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic