繁体   English   中英

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

[英]rerun program before main terminates

我有这个代码

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");
    }            
}

我希望行为是当输入“ 1”作为菜单值并打印“ first”时,程序不会终止,而是返回System.out.println("Enter menu number: "); 因此可以输入另一个菜单号,依此类推。 不知道该怎么做。

你可以做这样的事情

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");
        }

    }            
}

在您的代码上循环:

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