0
請參閱我的代碼以獲取問答遊戲。我一直試圖弄清楚如何在選項菜單正確編碼循環2天。一旦我知道如何正確編寫代碼,我就可以在餘下的其他問題所需的循環中進行編碼。輸入正確的輸入後需要退出循環
我現在編碼的方式會卡住「無效的選擇,請重試。」無限地。
有人請幫我用正確的代碼。 :(
一切我已經能夠找到與此相關的利用掃描儀輸入代替的JOptionPane。
package team1;
//this is required for JOptionPane to work
import javax.swing.JOptionPane;
//this allows for exception throwing
import java.io.*;
public class GameV2 {
public static void main(String[] args) throws IOException {
/**
* Version 2 Updates:
* - added 2 more sets of questions and answers
* - created a decision structure to determine the path of the game based on +
the user's menu choice
* - created a decision structure to indicate whether to the user whether an +
answer is correct or incorrect.
* - added point values to each question and a totalScore accumulator which +
displays at the end of the game.
*/
// display an introduction to the game.
JOptionPane.showMessageDialog(null, "Welcome to Team 1's Game Version 2!");
// prompt the user for his/her first name
String firstname;
firstname = JOptionPane.showInputDialog("What is your first name?");
// prompt the user for his/her last name
String lastname;
lastname = JOptionPane.showInputDialog("What is your last name?");
// display a customized hello message to the user
JOptionPane.showMessageDialog(null, "Hi, " + firstname + " " + lastname + "!");
**// create a menu and display it to the user
// then ask the user to choose an option
String menu = "1) See Rules and Play the Game\n"
+ "2) Play the Game\n"
+ "3) Exit\n"
+ "Please enter your choice: (1 or 2 or 3) ";
String userChoice = JOptionPane.showInputDialog(menu);
JOptionPane.showMessageDialog(null, "You chose option " + userChoice);
// display the rules
String rules = "Rules:\n"
+ "The game will display total 3 multiple choice questions," +
" with 4 possible answers per question.\n"
+ "Once you answer the question, the correct answer will be displayed" +
" and the game will advance to the next question.\n"
+ "If you answer the question correctly, you will gain a point.\n"
+ "Each point is added to a total score that will be displayed at the" +
"end of the game.\n";
// declare an integer that reads the user input
int numericChoice = Integer.parseInt(userChoice);
boolean valid = (numericChoice == 1 || numericChoice == 2 || numericChoice == 3);
if (numericChoice == 1){
// display the rules then start the game
JOptionPane.showMessageDialog(null, rules);
}
else if (numericChoice == 2){
// start the game
JOptionPane.showMessageDialog(null, "Let's play the game.\n");
}
else if (numericChoice == 3){
// exit the game
System.exit(0);
}
while (!valid){
JOptionPane.showMessageDialog(null, "Ivalid selection, please try again");
JOptionPane.showInputDialog(menu);
continue;
}
你永遠不會重新分配'valid'一次爲假,所以它永遠是錯誤的。 – Compass