Java怎么实现返回上级菜单请用Java写一串简单的代码
时间: 2024-02-13 15:02:03 浏览: 68
如何用java实现下拉菜单
4星 · 用户满意度95%
以下是一个简单的Java代码示例,演示如何通过递归函数实现返回上级菜单:
```java
import java.util.Scanner;
public class Menu {
public static void main(String[] args) {
showMainMenu();
}
public static void showMainMenu() {
System.out.println("1. 子菜单1");
System.out.println("2. 子菜单2");
System.out.println("3. 返回上级菜单");
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1:
showSubMenu1();
break;
case 2:
showSubMenu2();
break;
case 3:
System.out.println("返回上级菜单");
showMainMenu();
break;
default:
System.out.println("无效的选择");
showMainMenu();
break;
}
}
public static void showSubMenu1() {
System.out.println("1. 子菜单1-1");
System.out.println("2. 子菜单1-2");
System.out.println("3. 返回上级菜单");
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("执行子菜单1-1");
break;
case 2:
System.out.println("执行子菜单1-2");
break;
case 3:
System.out.println("返回上级菜单");
showMainMenu();
break;
default:
System.out.println("无效的选择");
showSubMenu1();
break;
}
}
public static void showSubMenu2() {
System.out.println("1. 子菜单2-1");
System.out.println("2. 子菜单2-2");
System.out.println("3. 返回上级菜单");
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("执行子菜单2-1");
break;
case 2:
System.out.println("执行子菜单2-2");
break;
case 3:
System.out.println("返回上级菜单");
showMainMenu();
break;
default:
System.out.println("无效的选择");
showSubMenu2();
break;
}
}
}
```
在该示例中,`showMainMenu()`函数显示主菜单,并根据用户输入调用不同的子菜单函数。当用户选择“返回上级菜单”时,调用`showMainMenu()`函数以返回上一级菜单。子菜单函数的实现类似,只是菜单内容不同。
阅读全文