无法在基本类型char上调用equals(char)

时间:2013-09-13 08:21:08

标签: java

我是编程并尝试坚持基本猜谜游戏的新手,但我有这个错误。需要一些帮助,因为我已经将'猜测'设置为char,然后想要将它与字符数组进行比较,但尝试了几种不同的方法,但还没有快乐。

它给出了底部if语句的错误:

(guess.equals(wordContainer[j]))

提前致谢。

我的代码:

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;

            }           
        }
    }   
}

2 个答案:

答案 0 :(得分:9)

将基元与==进行比较。如果您将char转换为包装类Character,则可以使用.equals()

要么改变

  1. char guess;Character guess;

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

答案 1 :(得分:2)

equals()是一个方法,它包含在Object类中,并通过继承传递给在java中创建的每个类。由于它是一种方法,因此只能通过对象而不是基元来调用它。

您应该像这样比较变量guess

if(guess==wordContainer[j]) {
希望它有所帮助。