JAVA Hangman程序在特定索引处显示字母,处理单词中的多个char实例

时间:2019-03-20 15:45:30

标签: java loops while-loop

if (posOfGuessLetter == -1)
    {
        System.out.print("Your letter was not found in the 
        spaces provided");
    } //if
if (posOfGuessLetter == 0)
    {
        displayWordAsDashes = (guessLetter + 
        displayWordAsDashes.substring(posOfGuessLetter + 1));
        displayWord = 
        displayWordAsDashes.substring(posOfGuessLetter + 1);
    } //if
if (posOfGuessLetter == 9)
    {
    displayWordAsDashes = (displayWordAsDashes.substring(0, 
    posOfGuessLetter) + guessLetter);
    displayWord = (displayWordAsDashes.substring(0, 
    posOfGuessLetter));
    } //if
else
    {
        displayWordAsDashes = (displayWordAsDashes.substring(0, 
        posOfGuessLetter) + guessLetter + 
        displayWordAsDashes.substring(posOfGuessLetter + 1));
        displayWord = (displayWordAsDashes.substring(0, 
        posOfGuessLetter) + 
        (displayWordAsDashes.substring(posOfGuessLetter + 1)));
    }

while (displayWord.contains(guessLetter))
    {
        displayWordAsDashes = (displayWordAsDashes.substring(0, 
        posOfGuessLetter) + guessLetter + 
        displayWordAsDashes.substring(posOfGuessLetter + 1));
        displayWord = (displayWordAsDashes.substring(0, 
        posOfGuessLetter) + 
        (displayWordAsDashes.substring(posOfGuessLetter + 1)));
    } //while
    } //else
System.out.print("The updated word is: " + 
displayWordAsDashes);

我正在尝试创建一个hangman程序,在这一部分中,它将检查用户输入的索引位置以查找他们想要在单词中找到的字符,然后删除该索引上的破折号并显示他们刚刚猜到的字母。但是,如果单词具有相同字母的两个字母(即naRRowing,100ps),我的程序不会同时显示两个字母,这就是我试图对while循环进行最后编程的方式。谁能告诉我我搞砸了吗?

1 个答案:

答案 0 :(得分:0)

我没看到您犯了什么错误,但是pos == 0和pos == 9都是多余的,因为

aString.substring(aString.length());

aString.substring(0, 0);

都返回空字符串。

如果您不必跟踪字母的位置,则可以执行以下操作:

private String wordToGuess = "hangman";
private String guessedSoFar = wordToGuess.replaceAll(".", "-");
private String leftToGuess = wordToGuess;

public String guess(char c) {
    for(int i = 0 ; i < leftToGuess.length() ; i++) {
        if(leftToGuess.charAt(i) == c) {
            guessedSoFar = guessedSoFar.substring(0, i) + c + guessedSoFar.substring(i + 1);
        }
    }
    leftToGuess = leftToGuess.replace(c, '-');
    return guessedSoFar;
}