• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Appending to StringBuffer

 
Mary Taylor
Ranch Hand
Posts: 327
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have been looking at what has to be a simple problem for too long. I thought I just had a basic problem with the for loop, but with Debug, I find the append is not happening. Here's the code:
String pagePath = "CustomPath";
StringBuffer convertedPagePath = null ;
int i = 0;
for ( i = 0; i < pagePath.length(); i++ ) {
if (pagePath.charAt(i) == '/'){
convertedPagePath.append('_');
} // end if
else {
convertedPagePath.append(pagePath.charAt(i));
} // end else
} // end for
I would appreciate any heads up on this. I know this is elementary, but I'm just seeing the same thing over and over.
Betty
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
convertedPagePath is initially null and is never assigned any other value. This code should throw a NullPointerException.
 
Mary Taylor
Ranch Hand
Posts: 327
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are right; that is the message I am getting. I have looked in Deitel and Deitel and other places and finally submitted this issue because I didn't see why I was getting this message. What does
do?
Thanks
[ October 26, 2002: Message edited by: Betty Schwartz ]
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It will append the i'th character of pagePath to convertedPagePath.
But it can't do this if convertedPagePath is null! You need to put a real StringBuffer object into that variable:
StringBuffer convertedPagePath = new StringBuffer();
[ October 26, 2002: Message edited by: Ron Newman ]
 
Mary Taylor
Ranch Hand
Posts: 327
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ouch! Thanks! I KNEW I was not going to be proud of myself after you told me.
Thanks again.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic