2

好的,我是 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");
        }
     }
 }

案例一完成执行后,程序退出。如何将控制权交还给 main,以便它可以重新开始,直到用户故意退出?

4

5 回答 5

8

将 main 中的代码提取到一个新函数中,然后调用该函数以传递控制权并重新开始。

于 2012-08-02T09:21:49.373 回答
1
boolean exitLoop = false;
while (!exitLoop) { 
    // insert code here
}
于 2012-08-02T09:22:51.907 回答
1

引入一个变量:

boolean run = true;

将您的代码放在一个循环中:

while(run){
    //your code
}

如果用户选择退出,只需将运行设置为false,程序就会退出。

于 2012-08-02T09:25:04.690 回答
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");
        }
       }
     }
 }
于 2012-08-02T10:22:48.207 回答
0

您可以递归地调用 main (不推荐),或者更好地遵循@ipavlic 给出的答案并将其放入循环中,就像@Dahaka 等其他人所说的那样。

于 2012-08-02T16:45:07.430 回答