gpt4 book ai didi

java - Java中的组合锁赋值

转载 作者:行者123 更新时间:2023-12-01 22:14:55 25 4
gpt4 key购买 nike

我有一个作业,其中有一个密码锁箱,里面有一个 4 个字母的单词作为组合,玩家必须通过一次猜测一个字母来尝试猜测该组合。对于每一轮,应该输出一条线索来显示一个人的猜测与实际单词的接近程度。如果猜测中的字母也在密码锁中处于相同位置,则输出匹配的字母。如果该字母在单词中但不在同一位置,则输出 +;当单词中根本不存在该字母时,则输出 * 。所有这些字符都添加到单个字符串中以显示结果。

我尝试用 Java 编写所有这些内容,但它返回一个错误的结果,前面有一个 null。有人可以帮我解决这些问题吗?

public class CombinationLock
{
private String lock;
private String guess;
private String guessLetter1;
private String guessLetter2;
private String guessLetter3;
private String guessLetter4;
private String lockLetter1;
private String lockLetter2;
private String lockLetter3;
private String lockLetter4;
private String modifiedGuess;
private char combinationLetter;
private char guessLetter;

public CombinationLock(String newLock)
{
lock = newLock;
}

public String getClue(String newGuess)
{
guess = newGuess;
for(int i = 0; i < lock.length(); i++)
{
combinationLetter = lock.charAt(i);
guessLetter = guess.charAt(i);

if(i == 0)
{
lockLetter1 += combinationLetter;
guessLetter1 += guessLetter;
}
else if(i == 1)
{
lockLetter2 += combinationLetter;
guessLetter2 += guessLetter;
}
else if(i == 2)
{
lockLetter3 += combinationLetter;
guessLetter3 += guessLetter;
}
else if(i == 3)
{
lockLetter4 += combinationLetter;
guessLetter4 += guessLetter;
}

if(combinationLetter == guessLetter)
{
modifiedGuess += combinationLetter;
}
else if(guessLetter1 == lockLetter1 || guessLetter1 == lockLetter2 || guessLetter1 == lockLetter3 || guessLetter1 == lockLetter4)
{
modifiedGuess += '+';
}
else if(guessLetter2 == lockLetter1 || guessLetter2 == lockLetter2 || guessLetter2 == lockLetter3 || guessLetter2 == lockLetter4)
{
modifiedGuess += '+';
}
else if(guessLetter3 == lockLetter1 || guessLetter3 == lockLetter2 || guessLetter3 == lockLetter3 || guessLetter3 == lockLetter4)
{
modifiedGuess += '+';
}
else if(guessLetter4 == lockLetter1 || guessLetter4 == lockLetter2 || guessLetter4 == lockLetter3 || guessLetter4 == lockLetter4)
{
modifiedGuess += '+';
}
else
{
modifiedGuess += '*';
}
}
return modifiedGuess;
}
}

public class MyProgram extends ConsoleProgram
{
public void run()
{
CombinationLock c1 = new CombinationLock("bird");
System.out.println(c1.getClue("barn"));
}
}


最佳答案

您需要初始化modifiedGuess变量,即

    public CombinationLock(String newLock)
{
lock = newLock;
modifiedGuess = "";
}

或者,您可以查看 StringUtils.difference 函数,它可能会给出类似的结果(如果允许分配)。

https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#difference(java.lang.String,%20java.lang.String)

关于java - Java中的组合锁赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58635870/

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