Reputation:
I am having problems with replacing the characters in the char array. I have tried the .replace
method, but it does not seem to work. So do you know how to replace the letters in the char array, with the char variable GuessedLetter
. This is code whole code I've developed so far:
import java.util.Scanner;
public class Hangman{
public static void main(String []args){
Scanner Input = new Scanner(System.in);
String[] CollectionOfWords = {"apple","banana","pear","plum","watermelon"};
int RadmNumber = (int) Math.ceil (Math.random() * CollectionOfWords.length);
String RadmWord = CollectionOfWords[RadmNumber];
System.out.println(RadmWord);
char[] GenRadmLetter = RadmWord.toCharArray();
char[] GenRadmLetter2 = RadmWord.toCharArray();
for (int x = 0; x<GenRadmLetter.length; x++){
GenRadmLetter[x]='?';
}
System.out.println(String.valueOf(GenRadmLetter));
Scanner input = new Scanner(System.in);
System.out.println("Hello. Guess a letter.");
char GuessedLetter = Input.next().charAt(0);
int RW = RadmWord.indexOf(GuessedLetter);
String GenRadmLetterStr = String.valueOf(GenRadmLetter);
}
}
Thank you,
Upvotes: 1
Views: 950
Reputation: 418
Firstly, variable names should begin with a lowercase letter as such. A capital letter implies a class type. This is a very standard convention when it comes to Java, and as such it helps readability when sharing code with others.
String radmWord = collectionOfWords[radmNumber];
Secondly, the method String.indexOf(Char)
only returns the first index of that character within the string. Since you would want to be replacing all occurrences of that character you would want to actually loop through the word checking each character to see if it is the character that was guessed. From there you could then replace that index within your guessing word. Take a look at this code I put together as an example, it should help you figure out what you need to do:
String randomWord = "apple";
String guessWord = "?????";
char guess = 'p';
for (int i = 0; i < randomWord.length(); i++) {
if (randomWord.charAt(i) == guess) {
char[] tempGuess = guessWord.toCharArray();
tempGuess[i] = guess;
guessWord = Arrays.toString(tempGuess);
}
}
Upvotes: 1
Reputation: 3019
You are trying to modify a String
.
This class is immutable, so when you try something such as:
GenRadmLetter[x]='?';
You are not modifying the data inside the RadmWord
.
What you could do, is something such as:
char[] GenRadmLetter2 = new char[RadmWord.length];
for (int x = 0; x < RadmWord.length; x++){
GenRadmLetter[x]='?';
}
String result = new String(GenRadmLetter2);
Although, you may wish to keep the displayed String
as a character array to allow easy changes to the display.
Upvotes: 1