破折号变成猜测的字母

时间:2017-02-12 04:18:36

标签: java

我的程序目前取一个随机单词,根据单词中有多少个字母变成破折号。然后我确定是否有一个字母猜到了,但是我无法弄清楚如何正确猜到字母会相应地替换破折号。我在网站上查看了可能的解决方案,但无法为我当前的代码工作。

代码:

public String hiddenWord(){
     word = randomWord.getRandomWord();
     String dashes = word.replaceAll("[^ ]", " _ ");
     return dashes;
}

public String guessNotification(){
    if(word.indexOf(hv.keyChar)!=-1 && (hv.keyChar >= 'a' && hv.keyChar <= 'z')) {
        letterGuessed = "There is a " + hv.keyChar + " in the word";
    }
    else if(word.indexOf(hv.keyChar)==-1 && (hv.keyChar >= 'a' && hv.keyChar <= 'z')) {
        letterGuessed = "No " + hv.keyChar + " in the word";
        guesses++;
        System.out.println(guesses);

    }
    else{
        letterGuessed = "Not a valid letter";
    }
    return letterGuessed;
}

public void newGame() {
    hv.createNotification(this, size);  
    guesses = 0;
    System.out.println(word);
}
}

2 个答案:

答案 0 :(得分:0)

评论都是正确的。但您可能希望看到示例代码:添加一组正确的猜测:

displaymember

使用例如初始化数组&#39; &#39 ;.然后替换破折号:

char[] correct = new char[26];  // or more, depends on whether u use non ascii chars

应该这样做。

答案 1 :(得分:0)

以下是如何用正确的用户猜测替换相应短划线的逻辑

    public static String guessNotification(String word, char userGuess, StringBuilder dashes) {

        int guessedIndex = word.indexOf(userGuess);
        if (guessedIndex != -1 && (userGuess >= 'a' && userGuess <= 'z')) {

            letterGuessed = "There is a " + userGuess + " in the word";
            dashes.setCharAt(guessedIndex*3+1, userGuess);

        }

        else if (guessedIndex == -1 && (userGuess >= 'a' && userGuess <= 'z')) {

            letterGuessed = "No " + userGuess + " in the word";
            guesses++;

        }
        else {

            letterGuessed = "Not a valid letter";

        }

        return letterGuessed;

    }