题目

编写控制台交互菜单骨架程序:在屏幕上循环打印主菜单选项(如 1.添加 2.查询 3.修改 0.退出),根据用户输入的指令进入对应分支并提示,直到用户选择 0 时退出程序。

输入格式:每次输入一个整数菜单选项代号。

输出格式:输出菜单提示文字及对应分支的执行反馈信息。

数据范围与约定:选项代号为整数。

思路与算法

1. 菜单事件驱动循环
经典的交互循环:do { show_menu(); Scanner 输入(...); switch(choice) { ... } } while (choice != 0);。

2. 健全输入保护
在 switch 中增加 default 分支捕获无效选项,并在每次输入后清理输入流中的多余换行符,防止死循环。

完整程序

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextInt()) {
            int op = sc.nextInt();
            if (op == 0) {
                break;
            }
            if (op == 1) {
                int a = sc.nextInt();
                int b = sc.nextInt();
                System.out.println("1 add 2 mul 0 exit");
                System.out.println(a + b);
            } else if (op == 2) {
                int a = sc.nextInt();
                int b = sc.nextInt();
                System.out.println("1 add 2 mul 0 exit");
                System.out.println(a * b);
            }
        }
    }
}

运行示例

输入:

1
3 4
0

输出:

1 add 2 mul 0 exit
7