JAVA: Hangman 游戏我需要它来只揭示第一次出现的猜测

JAVA: Hangman game i need it to only reveal the first occurrence of the guess

我正在 class 介绍 Java,我们有一个处理刽子手游戏的项目。我已经完成了大部分代码,但我无法让这部分按照我想要的方式工作。首先,程序提示用户输入一个字母,我需要它在该字母第一次出现在单词中时显示出来。假设这个词是苹果,我输入 p,我只想去 _ p _ _ _ 而不是 _ pp _ _。我想我需要使用 indexof 或类似的东西,但我可以使用一些帮助来确定使用哪个以及如何应用它。

 for (int i = 0; i < word.length(); i++) { //check if the letter is correct
            if (word.charAt(i) == letter && wordToShow.charAt(i) == '_') 
            {   //checking only free spaces _
                System.out.println("Good!");
                wordToShow.setCharAt(i, letter);  //change '_' to the letter guessed
                guessed += letter;                  //save the letter
                guessed += '+';                     //mark the success
                if (wordToShow.indexOf("_") == -1) 
                {   //if there more unsolved letters?
                    return true;        //there is no '_' symbols, all letters on their places
                }      

您所需要做的就是在找到一个后停止检查。只需在 if 块中的所有其他内容之后插入一个 break 语句,它将退出 for 循环并停止检查后续字母:

for (int i = 0; i < word.length(); i++) { //check if the letter is correct
        if (word.charAt(i) == letter && wordToShow.charAt(i) == '_') 
        {   //checking only free spaces _
            System.out.println("Good!");
            wordToShow.setCharAt(i, letter);  //change '_' to the letter guessed
            guessed += letter;                  //save the letter
            guessed += '+';                     //mark the success
            if (wordToShow.indexOf("_") == -1) 
            {   //if there more unsolved letters?
                return true;        //there is no '_' symbols, all letters on their places
            }      
            break;
        }
}