Java新手求助:如何实现代码循环至开头或指定问题位置?
Hey Danny, great start on your quiz game! Let's fix that flow issue you're having—getting the retry logic to behave exactly how you want: back to the first question when retry is "yes", and back to the main menu when it's "no".
First, let's note a small syntax issue in your current code: that final while (retry.equals("yes")); line is floating without a matching do, which will cause a compiler error. We'll fix that as part of restructuring the code for better flow.
The key here is to split your code into logical sections: a main menu loop, and a separate quiz-playing loop. Let's break it down step by step:
- Extract quiz logic to a reusable method: Makes it easy to restart the quiz without reloading the main menu.
- Outer loop for main menu: Handles returning to the start when the user picks "no" on retry.
- Inner loop for quiz retries: Immediately restarts the quiz from question 1 when the user picks "yes".
Revised Code
import java.util.Scanner; public class MainGame { static Question[] questions = new Question[15]; public static void main(String[] args) { loadQuestions(); Scanner kb = new Scanner(System.in); String userChoice; // Outer loop: keeps us in the main menu until we decide to exit (add exit option later if needed) while (true) { // Show main menu and get valid user choice do { System.out.println("Welcome to The Not Very Possible Quiz! "); System.out.println("By: Danny Gill"); System.out.println("Type In 'Play' to start playing, or type in 'Records' to see your high scores from previous games."); userChoice = kb.nextLine().toLowerCase(); } while (!(userChoice.equals("play") || userChoice.equals("records"))); if (userChoice.equals("records")) { System.out.println("High Scores:"); // Add your high score logic here later } else if (userChoice.equals("play")) { String retry; // Inner loop: restart the quiz as long as user says "yes" do { playQuiz(kb); // Get valid retry input do { System.out.println("\nDo you want to play again?"); retry = kb.nextLine().toLowerCase(); } while (!(retry.equals("yes") || retry.equals("no"))); } while (retry.equals("yes")); // When retry is "no", exit inner loop and go back to main menu } } } // Reusable method to run the quiz from the first question private static void playQuiz(Scanner kb) { System.out.println("Get Ready!"); System.out.println(questions[0]); String userAnswer = kb.nextLine().toLowerCase(); if (userAnswer.equals("a")) { System.out.println(questions[1]); } else { System.out.println("Wrong!"); } } public static void loadQuestions() { questions[0] = new Question("Which concert is the cheapest?", "50 Cent", "Drake", "Rihanna", "2-Pac"); questions[1] = new Question("Who was the first president of the USA?", "Donald Trump", "John Adams", "George Washington", "George W. Bush"); questions[2] = new Question("Which country has the largest military?", "United States", "India", "China", "North Korea"); questions[3] = new Question("In Hockey how many players are on the ice for each team?", "6", "5", "7", "4"); questions[4] = new Question("What is Canada's national sport?", "Lacrosse", "Hockey", "Basketball", "Soccer"); questions[5] = new Question("Who was the first prime minister of Canada?", "Lester B. Pearson", "Stephen Harper", "John A. Macdonald", "Alexander Mackenzie"); questions[6] = new Question("What is the largest city in Canada?", "Calgary", "Toronto", "Montreal", "Vancouver"); questions[7] = new Question("How many continents are there?", "5", "6", "7", "8"); questions[8] = new Question("What is Pakistan's currency?", "Euro", "Dollar", "Rupee", "Yen"); questions[9] = new Question("Who is currently the richest person on Earth?", "Bill Gates", "Elon Musk", "Jeff Bezos", "Mark Zuckerberg"); questions[10] = new Question("Which planet is nearest to the sun?", "Earth", "Mercury", "Venus", "Saturn"); questions[11] = new Question("Who invented Ferrari?", "Sergio Marchionne", "Endo Ferrari", "Enzo Ferrari", "Bill Ferrari"); questions[12] = new Question("Who painted the Mona Lisa?", "Pablo Picasso", "Leonardo Who Cares", "Leonardo DiCaprio", "Leonardo Da Vinci"); questions[13] = new Question("In what year was Google launched on the web?", "1998", "2000", "1997", "1990"); questions[14] = new Question("How often are the olympics held?", "3 Years", "4 Years", "5 Years", "2 Years"); } } // Don't forget your Question class! class Question { private String question; private String optionA; private String optionB; private String optionC; private String optionD; public Question(String question, String optionA, String optionB, String optionC, String optionD) { this.question = question; this.optionA = optionA; this.optionB = optionB; this.optionC = optionC; this.optionD = optionD; } @Override public String toString() { return question + "\nA: " + optionA + "\nB: " + optionB + "\nC: " + optionC + "\nD: " + optionD; } }
Key Changes Explained
playQuiz()Method: We moved all the quiz-running code here so we can easily call it whenever we want to start from the first question. This keeps the main method clean and avoids code repetition.- Main Menu Loop: The outer
while (true)ensures the program stays running (you can add an "Exit" option later if you want). This is where we return when the user selects "no" on retry. - Retry Loop: Inside the "Play" block, the inner
do-whileloop runs the quiz, then asks if the user wants to play again. If they say "yes", it loops back to runplayQuiz()again (starting from question 1). If "no", it exits the loop and returns to the main menu.
I also added the Question class with a proper toString() method—this fixes the "null" issue you mentioned earlier (since your original code didn't include how Question was defined, this ensures printing a Question shows the actual text and options).
内容的提问来源于stack exchange,提问作者Danny Gill

