方法甚至在循环外运行

时间:2019-07-01 23:22:27

标签: java

我有这种方法可以用作其他方法的菜单:

public static void menu(){

    boolean works = true;

    System.out.println("\n1 - Register Car\t2 - Register Client\t3 - Rent car\n4 - Returning car\t5 - Show list\t6 - Exit\n");
    System.out.print("Input: ");
    int operacao = scan.nextInt();

    do {
        if (operacao == 1) {
            cadVeiculo();
        } else if (operacao == 2) {
            cadCliente();
        } else if (operacao == 3) {
            locar();
        } else if (operacao == 4) {
            devolver();
        } else if (operacao == 5) {
            listar();
        } else if (operacao == 6){
            works= false;
        }
    } while (works);
}

我不了解的是,当我运行程序并按“ 6”时,程序停止,确定。但是,例如,当我按“ 1”注册汽车,然后按“ 6”退出程序时,该程序一直要求我输入另一个输入。

我期望的是,当我操作该程序并按“ 6”退出该程序时,它将完全停止该程序。

1 个答案:

答案 0 :(得分:1)

do-while 循环内移动printlnscanner.nextInt()行:

这是一个修改后的示例,仅打印出方法名称:

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    menu();
  }

  public static void menu() {
    Scanner scan = new Scanner(System.in);
    boolean works = true;
    do {
      System.out.println(
          "\n1 - Register Car\t2 - Register Client\t3 - Rent car\n4 - Returning car\t5 - Show list\t6 - Exit\n");
      System.out.print("Input: ");
      int operacao = scan.nextInt();
      if (operacao == 1) {
        System.out.println("cadVeiculo();");
      } else if (operacao == 2) {
        System.out.println("cadCliente();");
      } else if (operacao == 3) {
        System.out.println("locar();");
      } else if (operacao == 4) {
        System.out.println("devolver();");
      } else if (operacao == 5) {
        System.out.println("listar();");
      } else if (operacao == 6) {
        System.out.println("Goodbye!");
        works = false;
      }
    } while (works);
    scan.close();
  }
}

用法示例:

1 - Register Car    2 - Register Client 3 - Rent car
4 - Returning car   5 - Show list   6 - Exit

Input: 1
cadVeiculo();

1 - Register Car    2 - Register Client 3 - Rent car
4 - Returning car   5 - Show list   6 - Exit

Input: 3
locar();

1 - Register Car    2 - Register Client 3 - Rent car
4 - Returning car   5 - Show list   6 - Exit

Input: 4
devolver();

1 - Register Car    2 - Register Client 3 - Rent car
4 - Returning car   5 - Show list   6 - Exit

Input: 6
Goodbye!