Reputation: 153
This is the code I have written to check if a String in a string array and to replace the character holding the same position in another String array.
char[][] currentGuessArray = new char[currentGuessPhrase.length][];
for (int x = 0; x < currentGuessPhrase.length; x++) {
currentGuessArray[x] = currentGuessPhrase[x].toCharArray();
}
for (int x = 0; x < correctPhrase.length; x++) {
for (int a = 0; a < correctPhrase[x].length(); a++) {
if (correctPhrase[x].charAt(a) == guess) {
currentGuessArray[x][a] = guess;
}
}
}
//Convert chars back to string array
for (int x = 0; x < currentGuessArray[x].length - 1; x++){
currentGuessPhrase[x] = new String(currentGuessArray[x]);
}
For an example run: These are the values of currentPhrase
(5 entries):
sunny banana noun trained named
Variable Guess:
guess = "a"
Expected output:
_____ _a___a ____ __a____ _a___
Actual output:
_____ ______ ____ _______ _____
Also, for (int x = 0; x < currentGuessArray[x].length - 1; x++){
Throws:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at a.updateGuess(a.java:97)
at a.main(a.java:110)
Anyone who could help with either of the problems would be greatly appreciated, and this is not homework.
Upvotes: 1
Views: 607
Reputation: 61
yeah,it works as like user dasblinkenlight says.but,i think that we can do this,more simple method, follow is my code:
/**
* @param arr input array.
* @param searchString search string.
* @param replaceString replace string.
* @return replace of the string later,got the modified array.
*/
public static String searchString(String [] arr, String searchString, String replaceString) {
String result = "";
for (int i = 0; i < arr.length; i++) {
// search string whether or not exist.
boolean isExist = arr[i].contains(searchString);
if (!isExist) {
continue;
}
// replace string.
arr[i] = arr[i].replaceAll(searchString, replaceString);
}
for (int i = 0; i < arr.length; i++) {
result += arr[i] + (i != arr.length - 1 ? " " : "");
}
return result;
}
like this.it works when it called the method.
Upvotes: 0
Reputation: 726549
You need to fix the loop that converts back from character arrays to strings: you should go to the length of the currentGuessArray
array, not to the length of the first string in it:
//Convert chars back to string array
for (int x = 0; x < currentGuessArray.length ; x++) {
currentGuessPhrase[x] = new String(currentGuessArray[x]);
}
With this fix in place, your code works (demo).
Upvotes: 1