I turned a String into a char array and I was wondering if there was a way to replace 2 or more values in an array?
I'm working on a String guessing game that's a homework assignment, the User enters a sentence or word, then the user enters a letter, if the letter is part of the input, then the guessString updates, and replaces its '?' with the letter the user guessed.
For example:
User enters: racer
Original String: racer
Guess String:?????
Please guess a character
User enters: a
Original String: racer
Guess String:?a???
String input = "This is a string";
input = input.toLowerCase();
int inputLength = input.length();
System.out.println("You entered: " + input
+ "\n" + "The string length is: " + inputLength);
String answerString = "?".repeat(inputLength);
int answerStringLength = answerString.length();
System.out.println(answerString);
System.out.println(answerStringLength);
System.out.println("Guess a letter");
String guess = scan.nextLine();
System.out.println(guess);
int guessLength = guess.length();
System.out.println(guessLength);
while (guessLength != 1) {
guess = scan.nextLine();
guessLength = guess.length();
System.out.println(guessLength);
}
System.out.println(guess);
String guessRepeat = guess.repeat(3);
char guessChar=guessRepeat.charAt(2);
System.out.println(guessChar);
int checkGuess = input.indexOf(guess);
char[] answerStringChars = answerString.toCharArray();
answerStringChars[checkGuess]=guessChar;
String newAnswerString = String.valueOf(answerStringChars);
System.out.println(newAnswerString);
If the guessed letter is 'i'
Actual Results:
??i?????????????
Expected Results:
??i??i??????i???
Try this loop to replace all values, instead only the first one:
char[] answerStringChars = answerString.toCharArray();
for (int i = 0; i < answerString.length(); i++) {
if (input.charAt(i) == guessChar) {
answerStringChars[i] = guessChar;
}
}
String newAnswerString = String.valueOf(answerStringChars);
This should do the job.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments