Win a copy of Mesos in Action this week in the Cloud/Virtualizaton 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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic