如何在位置变化时替换字符串的特定位置

时间:2017-03-18 07:01:47

标签: java

嗨,我是一个新手编码器,我整夜都在努力解决这个问题。 我正在做一个刽子手游戏,用户必须输入他们想要猜的字母和他们想要检查的空格数。这个词当然是破折号所隐藏的。当用户在正确的空间中获得正确的字母时,我想要打印出隐藏的单词,并正确猜出字母和空格。例如

Word:循环

隐藏:-----

你想猜几封信: Ø

您想检查哪些空格: 1 2

隐藏:-oo -

我知道字符串是不可变的所以我必须创建一个新的字符串并用子字符串和用户输入的字母来连接它,但是位置会改变所以我必须重新命令每次校正它的方式是正确的吗?

我不允许使用数组,StringBuilder或StringBuffer

我希望我能够解释清楚

这是我到目前为止所做的事情

splashForm.getToolbar().hideToolbar();

1 个答案:

答案 0 :(得分:0)

这里唯一的问题是Scanner正在和你一起玩:

扫描仪的默认分隔符是white-space character因此当您输入选项时,包括空间扫描程序只读取第一个字符。

您的Substring方法也存在一些问题,我稍微调整了您的代码:

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    keyboard.useDelimiter("\\n"); \\---------- this is what tells scanner to use new line char as delimiter

    while (true) {
        System.out.println("Enter your difficulty: Easy (e), Intermediate (i), or Hard (h)");
        String diff = keyboard.next();

        String guess = "";
        String newGuess = "";
        String newWord = "loops";//RandomWord.newWord();

        int y = 0;
        int count = 0;
        for (int i = 0; i < newWord.length(); i++) {
            guess = newWord.replaceAll("[^#]", "-");
        }
        if ((diff.equalsIgnoreCase("e")) || (diff.equalsIgnoreCase("i")) || (diff.equalsIgnoreCase("h"))) {
            System.out.println("The secret word is:" + " " + newWord);
            System.out.println("The word is:" + " " + guess);

            System.out.println("Please enter the letter you want to guess");
            String letterInput = keyboard.next();

            System.out.println("Please enter the spaces you want to check (seperated by spaces)");
            String spaces = keyboard.next();

            for (String s : spaces.split("\\s")) {
                int x = Integer.valueOf(s);

                if (newWord.charAt(x) == letterInput.charAt(0)) {
                    System.out.println("Guess is correct for position " + x);
                    guess = guess.substring(0, x) + letterInput + guess.substring(x + 1, guess.length());
                    System.out.println(guess);
                }
            }
        }
    }
}

希望这有帮助!你几乎到了那里

祝你好运!