Java中的简单Hang子手。应该可以,但是不可以

时间:2019-06-03 12:05:03

标签: java

我正在尝试使它使用已猜出的字母和“ *”代替未猜到的字母来打印单词。

这是无效的部分。我分析了每一行,但是我找不到我该怎么做:(当我写字母“ e”时,我得到的是“ *******”而不是“ e ******”

 for (int i = 0; i < word.length(); i++) {
                        char letter = word.charAt(i);
                        if (command.equals(letter)) {
                            System.out.print(letter); 
                        }
                        else {
                            System.out.print('*');

                        }
 }

整个代码:

package hangman;
import java.util.Scanner;
import java.util.ArrayList;

public class Hangman {


public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);
    ArrayList<String> wordList = new ArrayList<String>();
    String word = "economy";
    System.out.println("************");
    System.out.println("* Hangman *");
    System.out.println("************");
    System.out.println("");
    System.out.println("");

    while (true) {

    System.out.println("Choose a letter!");
    String command = reader.nextLine(); 
        if (command.length() == 1) {
            guess(command); 
                if (word.contains(command) && !wordList.contains(command)) {
                    wordList.add(command);
                    System.out.println(wordList.size());
                   // System.out.println(word.replaceAll("[^" + wordList + "]", "?"));
                    for (int i = 0; i < word.length(); i++) {
                        char letter = word.charAt(i);
                        if (command.equals(letter)) {
                            System.out.print(letter); 
                        }
                        else {
                            System.out.print('*');

                        }
                    }
                }
        }
        else {
            System.out.println("Write only 1 letter!");
        }

    System.out.println("Thank you for playing!");
    }
}

public static void guess(String command) {
    String word = "economy";
  if (word.contains(command)) {
      System.out.println("Yes, the letter - " + command + " - is in the word" );


  } else {
      System.out.println("The letter - " + command + " - is NOT in the word" );

  }

}

}

我知道我应该制作单独的方法,但是我只是想首先使它起作用(如果我现在把所有东西都放在一个地方,对我来说似乎更容易),然后我将使它变得不那么混乱< / p>

感谢帮助

4 个答案:

答案 0 :(得分:1)

您正在使用equals()参数调用char,它永远不会等于您在其上调用它的String ...

尝试这样的方法:

if (command.charAt(0) == letter) {

答案 1 :(得分:1)

总是很高兴编写一些简单的游戏!您的实现存在一些缺陷和逻辑问题,很难用语言来解释-因此,让我向您展示注释的代码。希望没关系,我对您的代码进行了一些重构:

import java.util.Scanner;
import java.util.ArrayList;

public class Hangman {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in); //initialize scanner for user input
        ArrayList<Character> guessedLetters = new ArrayList<Character>(); //already guesed chars (ant NOT Strings!)
        int guessCount = 0; //count guesses (because this can be more than guessedLetters.size() !)
        String word = "economy"; //your test word
        word = word.toUpperCase(); //normalize word to upper-case letters

        //print welcome banner
        System.out.println("************");
        System.out.println("* Hangman *");
        System.out.println("************\n\n");

        String command; //variable to hold the "command", outside of while

        //now the game loop begins (input is asked INSIDE WHILE CONDITION!)
        //if input is "exit", game exits
        System.out.print("Guess your first letter: ");
        while (!(command = reader.nextLine()).equalsIgnoreCase("exit")) {
            //check length right at beginning of loop!
            if (command.length() != 1) {
                System.out.println("Your input must be only one character!");
            } else {
                //get upper-case character from command
                char letter = command.toUpperCase().charAt(0);
                //check if guess is correct
                if (word.contains(String.valueOf(letter)) && !guessedLetters.contains(letter)) {
                    //add letter to guessed letters
                    guessedLetters.add(letter);
                    //display guess count
                    System.out.println("Correct! You already had " + (++guessCount) + " guess(es).");
                    //display game state
                    for (char c : word.toCharArray()) {
                        //short-hand comparison (ternary operator) of chars! Don't compare Strings with chars!
                        System.out.print(guessedLetters.contains(c) ? c : '*');
                    }
                } else {
                    System.out.println("No, that's wrong! You already had " + (++guessCount) + " guess(es).");
                }
            }
            System.out.print("\n\nGuess your next letter: ");
        }

        System.out.println("Thank you for playing!"); //say good bye
        reader.close(); //close scanner!
    }
}

当然,您仍然需要逻辑来检查游戏是赢还是输。但是既然一切都属于它了,那么对您来说这应该没问题!
我希望这有帮助!继续努力!

答案 2 :(得分:0)

您将String和char进行比较,因此结果始终为false。尝试替换此代码:

if (command.equals(letter)) {
    System.out.print(letter); 
}

通过此代码:

if (command.equals(Character.toString(letter)) {
    System.out.print(letter); 
}

来自Character的javadoc:

/**
 * Returns a {@code String} object representing the
 * specified {@code char}.  The result is a string of length
 * 1 consisting solely of the specified {@code char}.
 *
 * @param c the {@code char} to be converted
 * @return the string representation of the specified {@code char}
 * @since 1.4
 */
public static String toString(char c) {
    return String.valueOf(c);
}

注意:当您不再需要Scanner时,应该关闭该扫描器。

答案 3 :(得分:0)

正确的解决方案是替换您的测试:

if (command.equals(letter)) {
  ...
}

使用:

if (wordList.contains(Character.toString(letter))) {
  ...
}

在当前方法中,您正在将String与char进行比较,这将始终为false。另外,您只比较最后输入的字符,这意味着您将只显示最后猜出的字符,而不是所有正确猜出的字符。