Java - Hangman Game - 在StringBuffer变量上遇到charAt问题

时间:2015-12-10 17:47:10

标签: java char stringbuffer charat

所以我正在尝试使用返回随机单词的网站制作一个悬挂式游戏。我在刽子手游戏中使用那个随机词。

我坚持的是验证用户的猜测。这是代码,我只是将所有内容放在main中,然后在此工作之后为我做单独的方法来完成工作。

public static void main(String[] args) throws Exception {
    randomWord = TestingStuff.sendGet();
    int totalTries = 1;
    char[] guesses = new char[26];
    int length = randomWord.length();
    Scanner console = new Scanner(System.in);

    System.out.print("* * * * * * * * * * * * * * *"
            + "\n*    Welcome to Hangman!    *"
            + "\n* * * * * * * * * * * * * * *");
    System.out.println("\nYou get 10 tries to guess the word by entering in letters!\n");
    System.out.println(randomWord);
    /*
     Cycles through the array based on tries to find letter
     */
    while (totalTries <= 10) {
        System.out.print("Try #" + totalTries);
        System.out.print("\nWhat is your guess? ");
        String guess = console.next();
        char finalGuess = guess.charAt(0);
        guesses[totalTries - 1] = finalGuess; //Puts finalGuess into the array


            for (int i = 0; i < totalTries; i++) { //checks to see if the letter is already guessed
                if (finalGuess != guesses[i]) {
                    for (int j = 0; i < length; j++) { //scans each letter of random word
                        if (finalGuess.equals(randomWord.charAt(j))) {

                        }
                    }
                } else {
                    System.out.println("Letter already guessed, try again! ");
                }
            }
        }
    }

我坚持的是在while循环中,它说:

            for (int i = 0; i < totalTries; i++) { //checks to see if the letter is already guessed
                if (finalGuess != guesses[i]) {
                    for (int j = 0; i < length; j++) { //scans each letter of random word
                        if (finalGuess.equals(randomWord.charAt(j))) {

                        }
                    }
                } else {
                    System.out.println("Letter already guessed, try again! ");
                }
            }

它给了我一个错误说&#34; char不能被解除引用&#34;。我在这里错过了什么吗?

1 个答案:

答案 0 :(得分:3)

finalGuess是原始char - 您无法在其上使用equals等方法。您可以使用char运算符比较两个==

if (finalGuess == randomWord.charAt(j)) {