我是一名学生,目前正在学习基本的 Java 课程。我正在编写一个代码,该代码要求用户输入游戏以“开始”和“退出”。所以我分别选择了字符串“S”和“Q”。如果用户输入 S,则游戏继续。如果用户输入 Q,程序会显示“感谢播放”或其他内容。如果用户输入的不是 S 和 Q,程序会再次询问,直到它得到一个有效的输入。除了错误检查部分,我几乎把所有东西都弄对了。任何可能的建议来修复我的代码?
先感谢您!:)
(部分代码)
Scanner scan = new Scanner(System.in);
String userInput;
boolean game = false;
System.out.println("Welcome to the Game! ");
System.out.println("Press S to Start or Q to Quit");
userInput = scan.nextLine();
if (userInput.equals("S")){
game = true;
} else if (userInput.equals("Q")){
game = false;
} else {
do {
System.out.println("Invalid input! Enter a valid input: ");
userInput = scan.nextLine();
} while (!"S".equals(userInput)) || (!"Q".equals(userInput)); // I'm not sure if this is valid???
}
if (userInput.equals("S")){
///// Insert main code for the game here////
} else if (userInput.equals("Q")){
System.out.println("Thank you for playing!");
}