简体   繁体   中英

Cannot invoke equals(char) on the primitive type char

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

  1. char guess; to Character guess;

    or

  2. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM