簡體   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