好的,我是Java的新手,我遇到了一个问题。当switch语句的某个部分完成执行时,我正试图让程序从main重新开始。这是我的代码:
import java.util.Scanner;
public class Test{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int ans;
System.out.println("Choose an option");
System.out.print("1: To see members\n2: To add member\n3: To delete a member\n Option: ");
ans = input.nextInt();
switch(ans){
case 1:
//code to see members
break;
case 2:
//code to add members
break;
case 3:
//code to delete members
break;
default:
System.out.println("Invalid option");
}
}
}
案例一完成后,程序退出。如何将控制权传递回主数据库,以便它可以再次启动,直到用户有意退出?
答案 0 :(得分:8)
将main中的代码解压缩到一个新函数中,然后调用该函数来传递控制并重新开始。
答案 1 :(得分:1)
boolean exitLoop = false;
while (!exitLoop) {
// insert code here
}
答案 2 :(得分:1)
引入一个变量:
boolean run = true;
将代码置于循环中:
while(run){
//your code
}
如果用户选择退出,只需将运行设置为false
,程序将退出。
答案 3 :(得分:0)
试试这个....
import java.util.Scanner;
public class Test{
public static void main(String[] args){
boolean run = true;
while(run){
Scanner input = new Scanner(System.in);
int ans;
System.out.println("Choose an option");
System.out.print("1: To see members\n2: To add member\n3: To delete a member\n4: To end the program\n Option: ");
ans = input.nextInt();
switch(ans){
case 1:
//code to see members
break;
case 2:
//code to add members
break;
case 3:
//code to delete members
break;
case 4:
//it will end the program
run=false;
break;
default:
System.out.println("Invalid option");
}
}
}
}
答案 4 :(得分:0)
你可以递归调用main(不推荐),或者更好,按照@ipavlic给出的答案,把它放在像@Dahaka这样的其他人说的循环中。