gpt4 book ai didi

java - 此 KnockKnockProtocol 类的构造函数代码中的 Java bug 在哪里?

转载 作者:行者123 更新时间:2023-12-01 11:18:23 26 4
gpt4 key购买 nike

我正在研究以下名为 KnockKnockServer and KnockKnockClient. 的客户端/服务器代码它还有一个名为 KnockKnockProtcol 的辅助类。 ,它负责 KnockKnock 笑话的顺序。

我想修改它,以便您可以在特定的笑话处启动程序。现在的情况是,你必须从第一个笑话开始。

这是对 KnockKnockProtocol 的尝试:

public class KnockKnockProtocol {

int ourstep;

public KnockKnockProtocol (int step) {
this.ourstep = step;
}

private static final int WAITING = 0;
private static final int SENTKNOCKKNOCK = 1;
private static final int SENTCLUE = 2;
private static final int ANOTHER = 3;

private static final int NUMJOKES = 5;

private int state = WAITING;
int currentJoke = ourstep; //we initialize the step here

private String[] clues = { "Turnip", "Little Old Lady", "Atch", "Who", "Who" };
private String[] answers = { "Turnip the heat, it's cold in here!",
"I didn't know you could yodel!",
"Bless you!",
"Is there an owl in here?",
"Is there an echo in here?" };

public String processInput(String theInput) {
String theOutput = null;

if (state == WAITING) {
theOutput = "Knock! Knock!";
state = SENTKNOCKKNOCK;
} else if (state == SENTKNOCKKNOCK) {
if (theInput.equalsIgnoreCase("Who's there?")) {
theOutput = clues[currentJoke];
state = SENTCLUE;
} else {
theOutput = "You're supposed to say \"Who's there?\"! " +
"Try again. Knock! Knock!";
}
} else if (state == SENTCLUE) {
if (theInput.equalsIgnoreCase(clues[currentJoke] + " who?")) {
theOutput = answers[currentJoke] + " Want another? (y/n)";
state = ANOTHER;
} else {
theOutput = "You're supposed to say \"" +
clues[currentJoke] +
" who?\"" +
"! Try again. Knock! Knock!";
state = SENTKNOCKKNOCK;
}
} else if (state == ANOTHER) {
if (theInput.equalsIgnoreCase("y")) {
theOutput = "Knock! Knock!";
if (currentJoke == (NUMJOKES - 1))
currentJoke = 0;
else
currentJoke++;
state = SENTKNOCKKNOCK;
} else {
theOutput = "Bye.";
state = WAITING;
}
}
return theOutput;
}
}

在 Server 类中,我这样调用 KnockKnockProtocol:

    /* omitting boilerplate code */
String inputLine, outputLine;

// Initiate conversation with client
KnockKnockProtocol kkp = new KnockKnockProtocol(2);
outputLine = kkp.processInput(null);
out.println(outputLine);

while ((inputLine = in.readLine()) != null) {
outputLine = kkp.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals("Bye."))
break;

问题是,当我运行代码时,我总是从“萝卜”笑话开始。如何才能从笑话列表中的任意笑话开始?我可以看到这个笑话是由 clues 数组控制的,但之后我就看不到它了。谢谢

最佳答案

如果您查看 KnockKnockProtocol 构造函数的输入,您会发现它通过 this.ourstep 直接影响 currentJoke 计数器,即然后用于引用 clues 数组。

因此,要从不同的位置开始,您可以在程序开头的构造函数中传递不同的数字。

希望有帮助!

关于java - 此 KnockKnockProtocol 类的构造函数代码中的 Java bug 在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31529310/

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