gpt4 book ai didi

java - 填写 "secret word"字母

转载 作者:行者123 更新时间:2023-12-01 13:19:26 28 4
gpt4 key购买 nike

我正在做一个刽子手项目。我已经让大部分代码正常工作了。

我无法工作的部分是“ secret 单词”有多个相同的字母。例如“hello”有 2 个“l”。

这是代码部分的代码,如果猜测正确,它将“----”(hello)替换为猜测的字母:

int pos = $Input.indexOf($Guessed); 

if (pos == -1)
{
System.out.print("Search string '" + $Guessed + "' not found");
}
else
{
System.out.println("\nSearch string found at " + (pos + 1));
pos = $Input.indexOf($Guessed);
String before = $Display.substring(0, pos);
String after = $Display.substring(pos + $Guessed.length());
System.out.println(before + $Guessed + after);

$Display = before + $Guessed + after;
System.out.println($Display);
$GuessAmt++;
}

我在这里查看了各种答案,但到目前为止我还无法找到答案。显然,如果有人猜到“l”,那么“-----”就会变成“--ll-”(你好)。

我并不是在找人为我编写这个代码,因为我喜欢挑战,但如果有一点提示就太好了!!

显然,通过查看我的代码,您可能会猜测不幸的是我们还不允许使用数组。这实际上只是对 Java 类的介绍。

如有任何帮助,我们将不胜感激。

编辑:需要明确的是,目前它只执行第一个“l”,而不是(hello)的两个“l”。

编辑:更改为此。然而,现在它一遍又一遍地重复“inside if”打印语句。不知道如何解决这个问题!

int pos = $Input.indexOf($Guessed); 

if (pos == -1)
{
System.out.print("Search string '" + $Guessed + "' not found");
}
else
{
//System.out.println("\nSearch string found at " + (pos + 1));

for(int i=0;i<$StrLength;i++)
{
System.out.println(i);
if($Input.charAt(i) == $Guessed.charAt(0))
{
i = $Input.indexOf($Guessed);
String before = $Display.substring(0, i);
String after = $Display.substring(i + 1);
System.out.println("inside if" + before + $Guessed + after);
$Display = before + $Guessed + after;
}
}



System.out.println($Display);



$GuessAmt++;
}

最佳答案

如果您仍然想使用 indexOf,您也可以使用它的重载版本来确保您已经完成了所有字母的出现:

int index = str.indexOf('l');
while(index >= 0) {
// FILL THE BLANKS WITH THE LETTER
index = str.indexOf('l', index +1);
}

关于java - 填写 "secret word"字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22161092/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com