I have a method called displayWord that is supposed to compare each index of an array with another array and if the indexes match, it is supposed to execute this line displayedWord[i] = wordArray[i]
. When I print the displayedWord, they are all question marks even thought the print statement executes so I know it is going into the if block.
Why is displayedWord always questions marks when I print it?
public static void displayWord(char[] correctGuesses, char[] wordArray) {
char[] displayedWord = new char[wordArray.length];
for(int i = 0; i < wordArray.length; i ) {
for(int j = 0; j < correctGuesses.length; j ) {
if(wordArray[i] == correctGuesses[j]) {
displayedWord[i] = wordArray[i];
System.out.println("they are the same");
} else displayedWord[i] = '?';
}
}
for(char c : displayedWord) {
System.out.print(c);
}
}
CodePudding user response:
That's because you are overeating the displayedWord, even if the char was found
Use break when you find the char to get out of the loop
here is the code
public static void displayWord(char[] correctGuesses, char[] wordArray) {
char[] displayedWord = new char[wordArray.length];
for(int i = 0; i < wordArray.length; i ) {
for(int j = 0; j < correctGuesses.length; j ) {
if(wordArray[i] == correctGuesses[j]) {
displayedWord[i] = wordArray[i];
System.out.println("they are the same");
break;
} else displayedWord[i] = '?';
}
}
for(char c : displayedWord) {
System.out.print(c);
}
}
CodePudding user response:
Currently you are not comparing the corresponding indices of the two arrays, because you have defined a double for loop with two different variables. With your code above it loops through each element of wordArray and compares every element of correctGuesses array for each wordArray element.
To get what you want, you only want to have one for loop which iterates n-times where n is the length of the smaller array.
CodePudding user response:
You are overriding the correct character at the next iteration when your code hits the else
case.
And it also seems like you don't need a nested loop to check whether a character in the array of guesses a matches a character in the containing correct characters (in case if characters at the same position need to be compared).
public static void displayWord(char[] correctGuesses, char[] wordArray) {
int len = Math.min(correctGuesses.length, wordArray.length);
char[] displayedWord = new char[len];
for(int i = 0; i < len; i ) {
if(wordArray[i] == correctGuesses[i]) {
displayedWord[i] = wordArray[i];
System.out.println("they are the same " wordArray[i]);
} else displayedWord[i] = '?';
}
for(char c : displayedWord) {
System.out.print(c);
}
}
main()
public static void main(String[] args) {
displayWord(new char[]{'a', 'b', 'c'},new char[]{'e', 'b', 'e'});
}
Output:
they are the same b
?b?