子串 - 替换

时间:2014-03-08 19:28:58

标签: java replace substring

制作goomba游戏。尝试用原始的虚线隐藏字替换用户猜测的字母。随着游戏的进行,隐藏的单词(例如“-------”)在替换字母时会添加破折号。任何人都可以让我知道我的替换代码在哪里我错了吗?

if (secretWord.charAt(one)==letterGuess)
{
    System.out.println("Yes");
    System.out.println("Your guess is in the word!");
    hidden= hidden.substring(0,one) + letterGuess + hidden.substring(++one);
    System.out.println("The updated word is: "+ hidden);
    System.out.println("Guesses Remaining: " + gCount);
}

1 个答案:

答案 0 :(得分:1)

代码对我来说似乎很好,我将其粘贴到主要方法中:

public class Letterguessing {

    public static void main(String[] args) {
        String secretWord = "hello";
        int one = 1;
        char letterGuess = 'e';
        String hidden = "-----";
        int gCount = 100;
        if (secretWord.charAt(one) == letterGuess) {
            System.out.println("Yes");
            System.out.println("Your guess is in the word!");
            hidden = hidden.substring(0, one) + letterGuess
                    + hidden.substring(++one);
            System.out.println("The updated word is: " + hidden);
            System.out.println("Guesses Remaining: " + gCount);

        }
    }

}

但可能你不只是希望玩家猜到位置“1”(secretWord.charAt(one))的字母,但你可能想检查所有字母,如果它们中的任何一个匹配 - 不是吗?< / p>