gpt4 book ai didi

java - 无法对原始类型 char 调用 equals(char)

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:39:46 27 4
gpt4 key购买 nike

我是编程新手,正在尝试破解一个基本的猜谜游戏,但我遇到了这个错误。需要一些帮助,因为我已将“猜测”设置为 char,然后想将它与 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;

}
}
}
}

最佳答案

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

要么改变

  1. char guess;Character guess;

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

关于java - 无法对原始类型 char 调用 equals(char),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18781564/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com