Loop to find and replace multiple instances of a char
So im trying to create a hangman like game. Ill add to it later but right now I just need the basics.
I'm trying to create a loop to find the position that a guessed letter is in then replace the appropriate asterisk with said letter.
What I have so far lets me run it but it replaces all the asterisks if the letter is in the phrase.
public class GuessingGame
public static void main(Stringargs)
//string and variable declerations
String guessingWord = "Dota is awsome";
String answer = "**** ** ******";
//in case the string length comes into play
length = guessingWord.length();
//Prompting the user to guess letter or phrase
guessedLetter = JOptionPane.showInputDialog(null, "Enter a letter or the full phrase\nif you think you know the answer");
//assigning variable to be the number of the position of the particular asterisk of the answer string
int a = guessingWord.indexOf(guessedLetter);
//if guessed letter is part of the asnwer
if(a != -1)
while(a >= 0)
sub = guessingWord.charAt(a);
answer = answer.replace(answer.charAt(a), sub);
a = guessingWord.indexOf(guessedLetter, ++a);
JOptionPane.showMessageDialog(null, "That letter is in the phrase!\n" + answer);
JOptionPane.showMessageDialog(null, "That letter is not in the phrase");
I had the code written in a way before that seemed like it worked but the GUI would crash after a correct letter guess was made.
I know i have some unused char's in there, Im going to remove it later once I get this part of my code to work, I can focus on the rest.
Re: Loop to find and replace multiple instances of a char
I would recommend you start out by writing down a list of steps to take in solving the problem. This will greatly improve the chances of the code doing what you want it to do when you get to writing code. If you get stuck post your list of steps and your code with the question.
Also please see the announcements page for the use of code tags.