0
我正在研究以下客戶端/服務器代碼,名爲KnockKnockServer and KnockKnockClient.它還有一個名爲KnockKnockProtcol的助手類,它負責KnockKnock笑話的順序。這個KnockKnockProtocol類的構造函數代碼中的Java錯誤在哪裏?
我想修改它,以便您可以在特定的笑話中啓動程序。就像現在,你必須從第一個笑話開始。
這是試圖爲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;
}
}
而在服務器級別的,我稱之爲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
數組控制,但之後我沒有看到它。感謝
您確定這是否行?你參考的代碼是我添加的..哪些沒有工作 – Coffee
這可能是因爲currentJoke設置的位置。刪除步驟類變量並將其替換爲currentJoke。在構造函數中設置currentJoke,並在你的其他函數中使用它(確保你使用this.currentJoke)。 只有你的數組等靜態元素應該在構造函數之外初始化。 –