在错误中执行/ while循环

时间:2017-08-28 12:10:14

标签: java loops

我正在尝试使用以下内容读取用户输入 - 变量' n' - 在会话中收到错误 - 找不到简单变量n。

public static void main(String[] args) {
    do{

        Scanner reader = new Scanner(System.in);  // Reading from System.in
        System.out.println("Enter your choice: ");
        int n = reader.nextInt(); // Scans the next token of the input as an int.

        switch(n){
            case 1: System.out.println("load_flight1()");
                break;
            case 2: System.out.println("load_flight2()");
                break;
            case 3: System.out.println("load_flight3()");
                break;
            case 4: System.out.println("generate_report()");
                break;
            case 5: System.out.println("exit()");
                break;
            default: System.out.println("Invalid menu choice");
                     System.out.println("press any key:");
         }
    }while ((n!=1) && (n!=2) && (n!=3) && (n!=4) && (n!=5));

有人可以找到我错的地方吗?

由于

1 个答案:

答案 0 :(得分:0)

n的范围位于do ... while Loop内,其中条件不是循环的一部分。 在循环之外声明它。

    Scanner reader = new Scanner(System.in); // Reading from System.in
    System.out.println("Enter your choice: ");
int n;
do {
    n = reader.nextInt();  
    switch (n) {
    case 1:
        System.out.println("load_flight1()");
        break;
    case 2:
        System.out.println("load_flight2()");
        break;
    case 3:
        System.out.println("load_flight3()");
        break;
    case 4:
        System.out.println("generate_report()");
        break;
    case 5:
        System.out.println("exit()");
        break;
    default:
        System.out.println("Invalid menu choice");
        System.out.println("press any key:");
    }

} while ((n != 1) && (n != 2) && (n != 3) && (n != 4) && (n != 5));