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

时间:2015-04-18 20:20:57

标签: java

我有这段代码

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"作为菜单值输入,"首先"打印时,程序不会终止但返回System.out.println("Enter menu number: ");,因此可以输入另一个菜单编号,依此类推。不知道怎么回事。

2 个答案:

答案 0 :(得分:2)

你可以做这样的事情

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

    }            
}

答案 1 :(得分:1)

在你的代码上放一个循环:

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
}