共計 1015 個字符,預計需要花費 3 分鐘才能閱讀完成。
實現 Java 二級菜單可以通過使用多層嵌套的菜單結構來實現。以下是一個簡單的示例代碼:
import java.util.Scanner;
public class Main {public static void main(String[] args) {Scanner input = new Scanner(System.in);
int choice1, choice2;
do {System.out.println("1. 一級菜單選項 1 ");
System.out.println("2. 一級菜單選項 2 ");
System.out.println("3. 退出 ");
System.out.print(" 請選擇一級菜單選項:");
choice1 = input.nextInt();
switch (choice1) {case 1:
do {System.out.println("1. 二級菜單選項 1 ");
System.out.println("2. 二級菜單選項 2 ");
System.out.println("3. 返回上一級菜單 ");
System.out.print(" 請選擇二級菜單選項:");
choice2 = input.nextInt();
switch (choice2) {case 1:
System.out.println(" 執行二級菜單選項 1 的操作 ");
break;
case 2:
System.out.println(" 執行二級菜單選項 2 的操作 ");
break;
case 3:
break;
default:
System.out.println(" 無效選項,請重新選擇 ");
}
} while (choice2 != 3);
break;
case 2:
System.out.println(" 執行一級菜單選項 2 的操作 ");
break;
case 3:
System.out.println(" 退出程序 ");
break;
default:
System.out.println(" 無效選項,請重新選擇 ");
}
} while (choice1 != 3);
input.close();}
}
在上面的示例中,首先展示了一級菜單選項,用戶可以選擇一級菜單中的選項。如果選擇了一級菜單中的某個選項,會顯示相應的二級菜單選項,用戶可以選擇二級菜單中的選項進行操作。用戶可以在任意時刻返回上一級菜單或退出程序。整個程序通過嵌套的 switch 語句實現了多層菜單的功能。您可以根據實際需求進行修改和擴展。
丸趣 TV 網 – 提供最優質的資源集合!
正文完