在此Java程序中,用戶應猜測1到100之間的數字,然後如果按S
它會顯示嘗試的摘要。問題是我正在輸入字符串並將其轉換爲數字,以便將其與範圍進行比較,但是我還需要能夠將該字符串用作菜單輸入。 更新如何在用戶猜測正確後讓程序回到菜單選項。用戶贏得打完,我想爲顯示其可以通過使用S-嘗試將字符串解析爲int時出錯
這裏以其他方式訪問的總結報告中的問題,是我的代碼
public class GuessingGame {
public static void main(String[] args) {
// Display list of commands
System.out.println("*************************");
System.out.println("The Guessing Game-inator");
System.out.println("*************************");
System.out.println("Your opponent has guessed a number!");
System.out.println("Enter a NUMBER at the prompt to guess.");
System.out.println("Enter [S] at the prompt to display the summary report.");
System.out.println("Enter [Q] at the prompt to Quit.");
System.out.print("> ");
// Read and execute commands
while (true) {
// Prompt user to enter a command
SimpleIO.prompt("Enter command (NUMBER, S, or Q): ");
String command = SimpleIO.readLine().trim();
// Determine whether command is "E", "S", "Q", or
// illegal; execute command if legal.
int tries = 0;
int round = 0;
int randomInt = 0;
int number = Integer.parseInt(command);
if (number >= 0 && number <= 100) {
if(randomInt == number){
System.out.println("Congratulations! You have guessed correctly." +
" Summary below");
round++;
}
else if(randomInt < number)
{
System.out.println("your guess is TOO HIGH. Guess again or enter Q to Quit");
tries++;
}
else if(randomInt > number){
System.out.println("your guess is TOO LOW. Guess again or enter Q to Quit");
tries++;
}
} else if (command.equalsIgnoreCase("s")) {
// System.out.println("Round Guesses");
// System.out.println("-------------------------");
// System.out.println(round + "" + tries);
} else if (command.equalsIgnoreCase("q")) {
// Command is "q". Terminate program.
return;
} else {
// Command is illegal. Display error message.
System.out.println("Command was not recognized; " +
"please enter only E, S, or q.");
}
System.out.println();
}
}
}
在此處發佈您的代碼。 – Simulant 2013-03-23 20:45:09
你說的不是問題,而是一個計劃。爲什麼你不能將它用作菜單中的輸入並將其轉換爲整數來比較範圍? – Michael 2013-03-23 20:47:11
OP想知道如何檢查'command'是否是一個數字。鍵入S或Q將會拋出一個'NumberFormatException',並且當前的代碼爲 – 2013-03-23 20:47:55