2017-08-28 174 views
-6

我正在尝试使用以下内容读取用户输入 - 在while会话中得到一个错误,即变量'n'-找不到简单的变量n。do/while循环内有错误

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

有人可以发现我要去哪里吗?

由于

+0

你的'int n = reader.nextInt();'在范围之外是不可见的。在循环之前引入局部变量'n'。 – DimaSan

+0

n实际上超出了范围...... –

+1

与描述的问题并不真正相关,但不要在每次迭代中创建Scanner。在你的循环之前声明和创建一个扫描器并在其中使用它。 – Pshemo

回答

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

'n = reader.nextInt();'应该在while循环中完成 –

+0

@NahuelFouilleul它在while循环中完成 – Jens

+0

您正在读取的值不会像这样在开关中进行分析;) – AxelH