【问题标题】:do / while loop inside a error [duplicate]在错误中执行/while循环[重复]
【发布时间】: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。在循环之前声明并创建一个扫描器并在其中使用它。

标签: java loops


【解决方案1】:

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

【讨论】:

  • n = reader.nextInt(); 应该在while循环中完成
  • @NahuelFouilleul 是在while循环中完成的
  • 您正在读取一个不会像这样在开关中分析的值 ;)
猜你喜欢
  • 1970-01-01
  • 2017-06-28
  • 1970-01-01
  • 2018-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-25
  • 1970-01-01
相关资源
最近更新 更多