I'm new to programming and trying to nut out a basic guessing game, but I have this error. Need some help as I've set 'guess' to char
, then want to compare it to the array of chars but tried a couple of different approaches but no joy yet.
It gives me the error on the if statement at the bottom containing:
(guess.equals(wordContainer[j]))
Thanks in advance.
My code:
import java.util.Scanner;
public class GuessingGame {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
String wordArray[] = {"aardvarks", "determine", "different", "greatness", "miserable", "trappings", "valuables", "xylophone"};
double rand = Math.random() * 8;
int x = 0;
x = (int)rand;
System.out.println(x);
String word = wordArray[x];
int wordCount = word.length();
System.out.println(word);
// System.out.println(wordCount);
char wordContainer[] = new char[wordCount];
char wordHiddenContainer[] = new char[wordCount];
String input;
char guess;
System.out.print("Enter your guess(a-z): ");
input = keyboard.next();
guess = input.charAt(0);
for ( int i = 0 ; i < wordCount ; i++ ) {
wordContainer[i] = word.charAt(i);
wordHiddenContainer[i] = '*';
}
System.out.println(wordContainer);
System.out.println(wordHiddenContainer);
for (int j = 0; j < word.length(); j++ ) {
if(guess.equals(wordContainer[j])) {
wordHiddenContainer[j] = guess;
}
}
}
}
Primitives are compared with ==
. If you convert the char
s to the wrapper classes Character
, then you can use .equals()
.
Either change
char guess;
to Character guess;
or
if(guess.equals(wordContainer[j]))
to if(guess == wordContainer[j]))
.
equals()
is a method that is contained in the Object class and passed on through inheritance to every class that is created in java. And since it is a method, it can be invoked only by objects and not primitives.
You should compare the variable guess
like this
if(guess==wordContainer[j]) {
hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With