简体   繁体   English

在主程序终止之前重新运行程序

[英]rerun program before main terminates

I have this code 我有这个代码

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter menu number: ");
    int value = scanner.nextInt();

    if (value == 1){
        System.out.println("first");
    } else if (value == 2) {
        System.out.println("second");
    } else if (value == 3) {
        System.out.println("third");
    } else {
        System.out.println("closing program");
    }            
}

I want the behavior to be that when "1" is entered as a menu value and "first" is printed, the program doesn't terminate but goes back to System.out.println("Enter menu number: "); 我希望行为是当输入“ 1”作为菜单值并打印“ first”时,程序不会终止,而是返回System.out.println("Enter menu number: "); so another menu number can be entered and so on. 因此可以输入另一个菜单号,依此类推。 Don't know how exactly to go about it. 不知道该怎么做。

You can do something like this 你可以做这样的事情

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    String userInput = "";
    while (true) {
        System.out.println("Enter menu number: ");
        userInput = scanner.next();
        if (userInput.trim().toUpperCase().equals("EXIT")) {
            break;
        }
        int value = Integer.parseInt(userInput);

        if(value == 1){
            System.out.println("first");
        }
        else if(value==2){
            System.out.println("second");
        }
        else if(value==3){
             System.out.println("third");
        }

    }            
}

Put a loop on your code: 在您的代码上循环:

public static void main(String[] args) {
  Scanner scanner = new Scanner(System.in);
  int value = -1;

  do { // Here you will loop until you enter something to "terminate"
    System.out.println("Enter menu number: ");
    value = scanner.nextInt();

    if (value == 1){
      System.out.println("first");
    } else if (value==2){
      System.out.println("second");
    } else if(value==3){
      System.out.println("third");
    } else{
      System.out.println("closing program");
    }
  } while (value != -1); // End condition
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM