This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Pls help ! on charAt()

 
jay lai
Ranch Hand
Posts: 180
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to write a small code to read a String, and then print out every other character of the string start at first character.
Here i have so far, but not sure how to read the next character, and not print it out.
Any suggestion or hint? I greately appreciate it.

public class Test {
public static void main (String [] args)
{
String str = "This is a test" ;
boolean startWord = true;
for (int i = 0; i < str.length() ; i++)
{
if (startWord)
System.out.println (str.charAt(i));
if (str.charAt(i) == ' ')
startWord = false;
else
startWord = true;
}
}
}
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not sure what startWord is supposed to be doing, but it looks like you're pretty close. What is it printing now? All the letters except a letter after a blank? If you're after every other letter you might toggle a boolean every time through the loop:

Or a better hint: Take a look at the for() statement. What part of that is telling it to look at the next character every time through the loop? Could you change it to look at every 2nd character?
 
Anupam Sinha
Ranch Hand
Posts: 1090
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jamieson
Do you mean somethin like this.
Orignal String : This is a test
Resulting String : Ti sats
Or
Resulting String : Ti s et
Or neither of these.
 
jay lai
Ranch Hand
Posts: 180
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Anupam Sinha
Do you mean somethin like this

Orrignal String : This is a test
Resulting String : Ti sats.

Yes. I am looking for something like this result.
Thanks
 
jay lai
Ranch Hand
Posts: 180
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Stan for your hint,
i got the answer,
Really appreciate it.
Anupam Sinha

I got the answer. thanks
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic