【问题标题】:Java - Hangman Game - trouble with charAt on StringBuffer variableJava - 刽子手游戏 - StringBuffer 变量上的 charAt 问题
【发布时间】:2016-03-16 11:27:10
【问题描述】:

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

我坚持的是验证用户的猜测。这是代码,我只是先将所有内容放在 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! ");
                }
            }

它给了我一个错误,说“char 不能被取消引用”。我在这里错过了什么吗?

【问题讨论】:

    标签: java char stringbuffer charat


    【解决方案1】:

    finalGuess 是一个原始的char - 你不能在上面使用诸如equals 之类的方法。您可以使用 == 运算符比较两个 chars:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-13
      • 1970-01-01
      • 2010-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-05
      相关资源
      最近更新 更多