Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在错误中执行/while循环_Java_Loops - Fatal编程技术网

Java 在错误中执行/while循环

Java 在错误中执行/while循环,java,loops,Java,Loops,我正在尝试使用以下命令读取用户输入- 在while会话中获取变量“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.ne

我正在尝试使用以下命令读取用户输入- 在while会话中获取变量“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));
有人能指出我哪里出了问题吗

谢谢

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

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

您的int n=reader.nextInt;在范围之外是不可见的。在do循环之前引入局部变量n。n实际上超出了范围……与所描述的问题没有实际关系,但不要在每次迭代中创建Scanner。在循环之前声明并创建一个扫描仪,并在其中使用。n=reader.nextInt;应该在一段时间内完成loop@NahuelFouilleul它是在循环中完成的,而您正在读取一个不会在开关中分析的值,就像这样;