gpt4 book ai didi

java - 尝试生成字符串作为 Word Solve 解决方案的提示

转载 作者:行者123 更新时间:2023-11-30 10:36:56 25 4
gpt4 key购买 nike

我正在尝试生成一个字符串作为世界解决方案的提示。

这就是我生成提示的内容,但我不确定如何更正这些错误。如果猜测在正确的位置猜到了正确的字符,则提示会显示该字符。如果单词中有字母,则在相应位置显示“+”。如果该字母不在单词中,则返回“*”。

例如,如果谜题的答案是“HARPS”,而猜测是“HELLO”,则提示将是“H****”。同样,如果猜测是“HEART”,则提示将是“H*++*”。

此外,wordLength 是从另一种方法生成的,该方法给出了解决方案中的字符数量。

public String getHint(String theGuess) {
for (int index = 0; index < wordLength; index++) {
if **(theGuess.charAt(index)** = solution.charAt(index)) {
hint.**setCharAt**(index, theGuess.charAt(index));
} else if **(theGuess.charAt(index)** = solution.indexOf(solution)) {
**hint.setCharAt**(index, "+");
} else {
**hint.setCharAt**(index, "*");
}
}
return hint;
}

错误是双星的。

对于 (theGuess.charAt(index) Eclipse 显示以下错误消息:

The left-hand side of an assignment must be a variable.

对于 hint.setCharAt,它告诉我:

The method setCharAt(int, String) is undefined for the type String.

最佳答案

您的代码中有许多问题需要修复:

  1. = 用于为变量赋新值。您想在比较两个值时使用 ==
  2. setCharAt()StringBuilder 的一个方法,不是字符串。这个最简单的解决方案是使用 += 将新字符连接到字符串。
    如果要使用StringBuilder,需要修复以下部分:
    • setCharAt() 的第二个参数应该是字符,而不是字符串。您需要将 "*""+" 周围的双引号更改为单引号,例如 '*'
    • setCharAt() 尝试替换特定索引处的字符。如果 StringBuilder 比您尝试替换的索引位置短,这将引发错误。您可以通过立即将 StringBuilder 设置为正确长度的字符串来解决此问题,例如
      hint = new StringBuilder("*****")
      由于您总是在构建器的末尾添加,因此您实际上应该只使用 append() 而不是 setCharAt() 并且您无需担心这一点索引位置问题。
  3. (theGuess.charAt(index) == solution.indexOf(solution) 不会搜索整个 solution 字符串以查看它是否包含当前字符。相反,您可以使用 indexOf() 来检查字符串是否包含该字符。此链接可能有帮助:How can I check if a single character appears in a string?

这是一个完整的程序,代码可以正常工作:

public class HelloWorld
{
public static void main(String[] args)
{
OtherClass myObject = new OtherClass();
System.out.print(myObject.getHint("HEART"));
}
}

选项 1 - 使用 += 添加到字符串:

public class OtherClass
{
private String solution = "HARPS";
private int wordLength = 5;

public String getHint(String theGuess) {
String hint = "";

for (int index = 0; index < wordLength; index++) {
if (theGuess.charAt(index) == solution.charAt(index)) {
hint += theGuess.charAt(index);
} else if (solution.indexOf(theGuess.charAt(index)) > 0) {
hint += "+";
} else {
hint += "*";
}
}

return hint;
}
}

选项 2 - 使用 StringBuilder:

public class OtherClass
{
private StringBuilder hint;
private String solution = "HARPS";
private int wordLength = 5;

public String getHint(String theGuess) {
hint = new StringBuilder();

for (int index = 0; index < wordLength; index++) {
if (theGuess.charAt(index) == solution.charAt(index)) {
hint.append(theGuess.charAt(index));
} else if(solution.indexOf(theGuess.charAt(index)) > 0) {
hint.append('+');
} else {
hint.append('*');
}
}

return hint.toString();
}
}

关于java - 尝试生成字符串作为 Word Solve 解决方案的提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40371293/

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