【发布时间】:2017-08-28 12:10:14
【问题描述】:
我正在尝试使用以下内容读取用户输入 - 在 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));
有人能看出我哪里出错了吗?
谢谢
【问题讨论】:
-
您的
int n = reader.nextInt();在范围之外是不可见的。在do循环之前引入局部变量n。 -
n 实际上超出范围......
-
与所描述的问题没有真正的关系,但不要在每次迭代中创建 Scanner。在循环之前声明并创建一个扫描器并在其中使用它。