【问题标题】:Hangman check if String is contained in the word and replace it?Hangman 检查单词中是否包含字符串并替换它?
【发布时间】:2017-06-28 21:00:30
【问题描述】:

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

我的问题是如何获得用户输入检查的字符串单词的位置,然后转到战板并用在该位置找到的单词更改“下划线(_)”。

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++;
    }

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

最好的问候 迈克尔德夫

【问题讨论】:

  • 你的问题很不清楚。你能说得更具体点吗?
  • 也许这是问题if (isTrue == true)
  • 我认为他指的是显示单词的主要逻辑,例如_ _ e _ _ e _ 并记住正确的chars。
  • 是的,我改了。
  • 扎布扎。 ACV 没关系,它只是检查输入是否为 1 位

标签: java string if-statement replace


【解决方案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
}

【讨论】:

  • 我试试我的但是 ty
猜你喜欢
  • 2014-01-25
  • 1970-01-01
  • 2019-04-25
  • 1970-01-01
  • 2013-12-23
  • 1970-01-01
  • 1970-01-01
  • 2020-06-21
相关资源
最近更新 更多