This week's book giveaway is in the JavaFX forum.
We're giving away four copies of Introducing JavaFX 8 Programming and have Herbert Schildt on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes String and for Loop Confusion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Introducing JavaFX 8 Programming this week in the JavaFX forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String and for Loop Confusion" Watch "String and for Loop Confusion" New topic

String and for Loop Confusion

Mike B.

Joined: Oct 14, 2008
Posts: 2
Good evening all,

I've been staring at the below problem and am more confused than before hand. I've done strings before and replaced letters within them but never in a for loop. I've only used the replace method which is something that we cannot use. Any guidance would be greatly appreciated.

Let word be a String variable referencing a non-empty string. Write a for loop that prints the string with all occurrences of the lowercase letter 'n' replaced with 'r'. For example, if word references the string "Kenny", then your code should print "Kerry". Do not use the replace() method of the String class.

When I've done for loops in the past it was for integers and when I try and code for chars & strings I get lost.
Ananth Chellathurai
Ranch Hand

Joined: Nov 21, 2007
Posts: 349


Are you aware of replaceAll() method in Strings?

Ananth Chellathurai

Ananth Chellathurai [Walk on software]
Mike B.

Joined: Oct 14, 2008
Posts: 2
No I haven't heard of it at all. Does it have the look and feel of the replace() method? If so then I'm hamstrung from using it.
Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
Lets think this through. Using a for loop, you'll want to examine each character of the String from the first to the last. If the current character is not an 'n', then print it, else print an 'r'. Look at the methods of String class. Which String methods do you think might be useful to you?
[ October 15, 2008: Message edited by: Garrett Rowe ]

Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 44460
"Mike B." please read the important administrative private message I have just sent you.

I agree. Here's the link:
subject: String and for Loop Confusion
It's not a secret anymore!