java中的字符串猜测符号

u5i3ibmn  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(350)

关闭。这个问题需要细节或清晰。它目前不接受答案。
**想改进这个问题吗?**通过编辑这个帖子来添加细节并澄清问题。

4个月前关门了。
改进这个问题
有一根线像:

String str = "###############";

有猜词,例如:

String guess = "Java"

用户必须猜单词:

User input:

Sava

sring应:

String str = "#a#a###########";

所有的符号都放在索引上 String 是不可变的类。
我选择了 Stringbuilder ```
for (int i = 0; i < length ; i++) {
if (rnd.charAt(i) == guess.charAt(i) && rnd.charAt(i) != '#'){
sb.append(rnd.charAt(i));
}
}

System.out.println(sb);

sb.delete(0, sb.length());
``` Stringbuilder 添加不在position上的正确符号 'i' ,但在最后的索引上。
例子:

guess word: Java

user input Sala:

System.out.println(sb);

############### aa

我怎样才能达到所需的结果?我应该用什么工具?
需要的结果:

Example:
guess word Java:

user input Sala:

System.out.println(sb);

# a#a###########
41ik7eoe

41ik7eoe1#

您可以按以下步骤进行:

public class Main {
    public static void main(String[] args) {
        String str = "#a#a###########";
        String guess = "Java";
        String input = "Sala";
        StringBuilder sb = new StringBuilder();
        int i;
        for (i = 0; i < str.length() && i < guess.length() && i < input.length(); i++) {
            // In case of a match, append the matched character
            if (guess.charAt(i) == input.charAt(i)) {
                sb.append(guess.charAt(i));
            } else {// Else append the placeholder symbol from `str`
                sb.append(str.charAt(i));
            }
        }

        // Append the remaining placeholder characters from `str`
        sb.append(str.substring(i));

        // Display
        System.out.println(sb);
    }
}

输出:


# a#a###########
lnxxn5zx

lnxxn5zx2#

像这样工作:

private static String word(){
    String guess = new Scanner(System.in).nextLine();
    return guess;
}

private static void guessWord(String[]arr) {
    int random = new Random().nextInt(arr.length);
    String rnd = arr[random];

    int length = 15;

    StringBuilder sb = new StringBuilder();
    String guess = "";

    int rndLength = length - rnd.length();
    int guessLength = length - guess.length();

    do {
        System.out.println("Enter a word: ");
        guess = word();

       if (sb.length() < length){
           for (int i = 0; i < length ; i++) {
               sb.append("#");
           }
       }

        for (int i = 0; i < length  && i < rnd.length() && i < guess.length();  i++) {
            if (rnd.charAt(i) == guess.charAt(i)){
                sb.setCharAt(i, rnd.charAt(i));
                sb.delete(length, sb.length());
            }
        }

        if (rnd.equals(guess)){
            System.out.println("Guess word: " + rnd);
            break;
        }else if (!rnd.equals(guess)) {
            System.out.println(sb);
        }
    }while (!rnd.equals(guess));
}

相关问题