我正在編寫客戶端/服務器猜測遊戲。輸入錯誤後無法輸入提示
我有一個guessGameServerHandler類,它處理一個遊戲的單個實例爲客戶(遊戲是多線程)
我也有在輸入客戶端類讀數,那麼該處理程序響應。
我需要輸出一個錯誤,如果用戶輸入一個字符串,而不是一個整數,然後循環回來,再次要求輸入,但似乎無法得到它的工作。有什麼建議麼?
客戶端代碼:(這是while循環一做,檢查是否輸入等於正確的號碼或沒有)
// Read in clients input
System.out.print("Enter guess: ");
guess = Integer.parseInt(stdin.readLine());
// send guess to server
out.write(String.format("%s%n", guess));
out.flush();
guessGameHandlerServer:
do {
try{
// Read in guesses from user
guess = Integer.parseInt(in.readLine());
}catch(NumberFormatException e){
}
gs.guess(guess);
String timeForm = decFor.format(gs.getTimeRemaining()/1000D);
// Check user input against target number & time left
if (gs.getTimeRemaining() < 1) {
System.out.println(ID + " - (LOSE)" + timeForm + "/" + gs.getGuesses());
client.close();
} else if (gs.getTimeRemaining() > 0 && guess > gs.getTarget() && guess < maxNum) {
out.write(String.format("HIGH:%s:%d%n", timeForm, gs.getGuesses()));
out.flush();
System.out.println(ID + " " + guess + "(HIGH)-" + timeForm + "s/" + gs.getGuesses());
} else if (gs.getTimeRemaining() > 0 && (guess < gs.getTarget() && guess > 0)) {
out.write(String.format("LOW:%s:%d%n", timeForm, gs.getGuesses()));
out.flush();
System.out.println(ID + " " + guess + "(LOW)-" + timeForm + "s/" + gs.getGuesses());
} else if (gs.getTimeRemaining() > 0 && guess == gs.getTarget()) {
out.write(String.format("WIN:%d%n", gs.getGuesses()));
out.flush();
System.out.println(ID + " " + guess + "(WIN)-" + timeForm + "s/" + gs.getGuesses());
} else if (gs.getTimeRemaining() > 0 && (guess >= maxNum || guess < 1)) {
out.write(String.format("ERR:%d%n", gs.getGuesses()));
out.flush();
System.out.println(ID + " ** (ERR out of range)" + timeForm + "/" + gs.getGuesses());
}
} while (true);
與當前的代碼,輸入字符串只是使客戶端線程關閉,不知道爲什麼。
這有效,但我也試圖發送一條消息到服務器,當客戶端輸入一個不正確的輸入。將'out.write'放在catch塊中似乎不起作用。 – Travisty
當用戶輸入錯誤的輸入時,你想發送給服務器的是什麼?您無法確定地發送「猜測」,因爲由於用戶輸入不正確而導致它沒有值。無論你想在這種情況下發送什麼,把它放在「catch」塊,然後是「flush」。它應該工作。 – AhmadWabbi