Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot invoke equals(char) on the primitive type char

Tags:

java

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;

            }           
        }
    }   
}
like image 669
Steve Andrews Avatar asked Dec 16 '22 06:12

Steve Andrews


2 Answers

Primitives are compared with ==. If you convert the chars to the wrapper classes Character, then you can use .equals().

Either change

  1. char guess; to Character guess;

    or

  2. if(guess.equals(wordContainer[j])) to if(guess == wordContainer[j])).

like image 75
Konstantin Yovkov Avatar answered Jan 31 '23 13:01

Konstantin Yovkov


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.

like image 27
Thirumalai Parthasarathi Avatar answered Jan 31 '23 13:01

Thirumalai Parthasarathi