You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java菜单功能实现疑问:执行选项后如何返回主菜单

Fixing the Menu Loop for Your MathTutor Program

Hey Lisa, great start on your MathTutor program! The trick to making the menu reappear after each operation is wrapping your menu logic in a loop that runs until the user picks the exit option. Let's break this down step by step.

Core Idea: Use a do-while Loop

A do-while loop is perfect here because it guarantees the menu will show at least once (even if the user immediately tries to exit), then checks if it should keep running after each iteration.

Modified Code with Working Menu Loop

Here's how to update your code to implement this logic, with comments explaining each key part:

import java.util.Scanner;
import java.util.Random;

public class MathTutor {
    // Create scanner for user input
    Scanner keyboard = new Scanner(System.in);
    // Declare variables
    int choice;
    Random generator = new Random();

    public MathTutor() {
        // Loop: show menu, handle choice, repeat until exit
        do {
            displayMainMenu();
            choice = keyboard.nextInt();
            
            // Handle each menu option with a switch statement
            switch(choice) {
                case 1:
                    runAdditionPractice();
                    break;
                case 2:
                    runSubtractionPractice();
                    break;
                case 3:
                    runMultiplicationPractice();
                    break;
                case 4:
                    System.out.println("Thanks for practicing! See you next time.");
                    break;
                default:
                    System.out.println("Whoops, that's not a valid option. Try again!");
            }

            // Add a blank line for readability between menu cycles
            System.out.println("\n");

        } while(choice != 4); // Keep looping until user selects exit (option 4)

        // Clean up the scanner to avoid resource leaks
        keyboard.close();
    }

    // Helper method to print the menu (keeps code organized!)
    private void displayMainMenu() {
        System.out.println("===== Math Tutor =====");
        System.out.println("1. Addition Practice");
        System.out.println("2. Subtraction Practice");
        System.out.println("3. Multiplication Practice");
        System.out.println("4. Exit Program");
        System.out.print("Enter your choice: ");
    }

    // Example addition practice logic (fill this out with your own!)
    private void runAdditionPractice() {
        int num1 = generator.nextInt(100);
        int num2 = generator.nextInt(100);
        System.out.printf("Solve: %d + %d = ?%n", num1, num2);
        
        int userAnswer = keyboard.nextInt();
        if(userAnswer == num1 + num2) {
            System.out.println("Perfect! That's correct.");
        } else {
            System.out.printf("Nice try, but the right answer is %d.%n", num1 + num2);
        }
    }

    // Placeholder for subtraction practice (add your logic here)
    private void runSubtractionPractice() {
        System.out.println("Subtraction practice is coming soon!");
    }

    // Placeholder for multiplication practice (add your logic here)
    private void runMultiplicationPractice() {
        System.out.println("Multiplication practice is coming soon!");
    }

    public static void main(String[] args) {
        new MathTutor();
    }
}

Key Details to Note

  • Loop Structure: The do-while runs first (shows menu, processes choice), then checks if choice !=4 to decide if it should loop again.
  • Separate Methods: I moved menu display and practice logic into their own methods (displayMainMenu(), runAdditionPractice()) to keep your code clean and easy to modify later.
  • Switch Statement: This neatly handles each menu option—after executing the selected practice, the break sends the program back to the start of the loop.
  • Scanner Cleanup: Always close your Scanner when you're done with it to avoid wasting system resources.

Quick Tip for Input Issues

If you notice weird behavior with input (like the menu skipping a prompt after entering an answer), add keyboard.nextLine(); after keyboard.nextInt(); calls. This clears the leftover newline character from the input buffer.

内容的提问来源于stack exchange,提问作者Lisa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:15:52