Hangman检查单词中是否包含String并替换它?

时间:2017-06-28 21:00:31

标签: java string if-statement replace

我在java中创建一个刽子手游戏。我不知道如何检查和更换它。一切正常,String字是正确的,游戏板很好。所以游戏板给我的长度为" _ _ _ _ _",例如。

我的问题是我如何才能获得用户输入检查字符串字的位置并转到战斗板并更改"下划线(_)"用这个词来找到这个位置。

public void gameStart(int topic) {
    String[] wordList = this.wordList.chooseTopicArray(topic);
    String word = this.wordList.pickRandom(wordList);
    String gameboard = spielbrettvorbereiten(word);
    Scanner userInput = new Scanner(System.in);

    for (int i = 0; i <= 16;) {

    System.out.println(gameboard);
    System.out.print("Write a letter ");

    String input = userInput.next();
    int length = input.length();
    boolean isTrue = letters.errateWortEingabe(length);

    if (isTrue == true) {
    if (word.contains(input)) {

    }


    } else {
       i = i - 1;
    }


    i++;
    }

我希望你们能帮助我,我很努力。

最诚挚的问候 MichaelDev

1 个答案:

答案 0 :(得分:1)

有几种方法可以实现hangman。我将向您展示一种易于理解的方法,而不是关注效率。

您需要知道最后一个单词并记住用户猜到的所有字符:

final String word = ... // the random word
final Set<Character> correctChars = new HashSet<>();
final Set<Character> incorrectChars = new HashSet<>();

现在,如果用户猜到一个字符,你应该更新数据结构:

final char userGuess = ... // input from the user
if (correctChars.contains(userGuess) || incorrectChars.contains(userGuess) {
    System.out.println("You guessed that already!");
} else if (word.contains(userGuess)) {
    correctChars.add(userGuess);
    System.out.println("Correct!");
} else {
    incorrectChars.add(userGuess);
    System.out.println("Incorrect!");
}

最后你需要打印单词为_ _ _ _的东西,依此类推。我们通过替换correctChars中包含的所有字符来完成此操作:

String replacePattern = "(?i)[^";
for (Character correctChar : correctChars) {
    replacePattern += correctChar;
}
replacePattern += "]";

final String wordToDisplay = word.replaceAll(replacePattern, "_");
System.out.println("Progress: " + wordToDisplay);

replacePattern可能看起来像(?i)[^aekqw](?i)匹配不区分大小写,[...]是要匹配的符号组,^否定组。因此,[...]中未包含的所有字符都将被替换。

并仔细检查游戏是否已完成:

if (wordToDisplay.equals(word)) {
    System.out.println("You won!");
} else if (incorrectChars.size() > 10) {
    System.out.println("You guessed wrong 10 times, you lost!");
} else {
    ... // Next round starts
}