Java 无法在原始类型 char 上调用 equals(char)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18781564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot invoke equals(char) on the primitive type char
提问by Steve Andrews
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.
我是编程新手并试图摆脱一个基本的猜谜游戏,但我有这个错误。需要一些帮助,因为我已将 'guess' 设置为char
,然后想将它与字符数组进行比较,但尝试了几种不同的方法,但还没有快乐。
It gives me the error on the if statement at the bottom containing:
它给了我底部 if 语句的错误,其中包含:
(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;
}
}
}
}
采纳答案by Konstantin Yovkov
Primitives are compared with ==
. If you convert the char
s to the wrapper classes Character
, then you can use .equals()
.
原语与==
. 如果将char
s转换为包装类Character
,则可以使用.equals()
.
Either change
要么改变
char guess;
toCharacter guess;
or
if(guess.equals(wordContainer[j]))
toif(guess == wordContainer[j]))
.
char guess;
到Character guess;
或者
if(guess.equals(wordContainer[j]))
到if(guess == wordContainer[j]))
。
回答by Thirumalai Parthasarathi
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.
equals()
是一个包含在 Object 类中的方法,并通过继承传递给在 java 中创建的每个类。由于它是一种方法,因此只能由对象而不是基元调用。
You should compare the variable guess
like this
你应该guess
像这样比较变量
if(guess==wordContainer[j]) {
hope it helps.
希望能帮助到你。