在Java中,初学者程序员可以使用循环结构来实现回到主菜单的功能。常见的循环结构有while循环、do-while循环和for循环。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean exit = false;
while (!exit) {
System.out.println("主菜单");
System.out.println("1. 选项一");
System.out.println("2. 选项二");
System.out.println("3. 退出");
System.out.print("请输入选项:");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("执行选项一");
break;
case 2:
System.out.println("执行选项二");
break;
case 3:
exit = true;
break;
default:
System.out.println("无效选项");
break;
}
}
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean exit;
do {
System.out.println("主菜单");
System.out.println("1. 选项一");
System.out.println("2. 选项二");
System.out.println("3. 退出");
System.out.print("请输入选项:");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("执行选项一");
break;
case 2:
System.out.println("执行选项二");
break;
case 3:
exit = true;
break;
default:
System.out.println("无效选项");
break;
}
} while (!exit);
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
for (;;) {
System.out.println("主菜单");
System.out.println("1. 选项一");
System.out.println("2. 选项二");
System.out.println("3. 退出");
System.out.print("请输入选项:");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("执行选项一");
break;
case 2:
System.out.println("执行选项二");
break;
case 3:
return;
default:
System.out.println("无效选项");
break;
}
}
}
}
以上是三种常见的循环结构,初学者程序员可以根据实际需求选择适合的循环方式来实现回到主菜单的功能。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云