在此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