我正在研究以下名为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;
问题在于,当我运行我的代码时,我总是从" Turnip"玩笑。我怎么做到这样我可以从笑话列表中的任意一个笑话开始?我可以看到这个笑话是由clues
数组控制的,但之后我没有看到它。感谢
答案 0 :(得分:1)
如果您查看KnockKnockProtocol
构造函数的输入,您会发现它会通过currentJoke
直接影响this.ourstep
计数器,然后用于引用clues
数组
因此,要从不同的位置开始,您可以在程序开头的构造函数中传入不同的数字。
希望有所帮助!