无法在基本类型char上调用equals(char) [英] Cannot invoke equals(char) on the primitive type char
问题描述
我是编程并尝试坚持基本猜谜游戏的新手,但我有这个错误。需要一些帮助,因为我已经将'猜测'设置为 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.
它给出了底部if语句的错误:
It gives me the error on the if statement at the bottom containing:
(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;
}
}
}
}
推荐答案
将基元与 ==
进行比较。如果将 char
转换为包装类 Character
,则可以使用 .equals ()
。
Primitives are compared with ==
. If you convert the char
s to the wrapper classes Character
, then you can use .equals()
.
更改
-
char guess;
到字符猜测;
或
if(guess.equals(wordContainer [j]))
to if(guess == wordContainer [j]))
。
这篇关于无法在基本类型char上调用equals(char)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!