循环变量无法解析为变量

时间:2015-11-18 23:47:03

标签: java

我有这个代码,我循环直到用户输入-1。但是,我收到错误:

  

键无法解析为变量

之前我使用过这段代码而且我没有遇到任何问题,所以我不确定为什么我会遇到这个问题。

System.out.println("\nEnter a number, -1 to stop : ");
do {
  int key = scan.nextInt();
  int result = interpolationSearch(integerArray, key);
  if (result != -1) {
    System.out.println("\n"+ key +" element found at position "+ result);
  }
    break;
} while (key != -1);    // quit 
System.out.println("stop");
}

2 个答案:

答案 0 :(得分:4)

您需要在do循环之外声明key,并且每次循环运行时都可以获得nextInt。此外,循环中不需要break语句。

System.out.println("\nEnter a number, -1 to stop : ");
int key;
do {
  key = scan.nextInt();
  int result = interpolationSearch(integerArray, key);
  if (result != -1) {
    System.out.println("\n"+ key +" element found at position "+ result);
  }      
} while (key != -1);    // quit 
System.out.println("stop");
}

答案 1 :(得分:2)

您需要在do循环之外声明int键。因为它是在循环内声明的,所以while条件不知道它。这被称为超出范围。以下是范围http://java.about.com/od/s/g/Scope.htm的一些示例和解释。

将其更改为:

System.out.println("\nEnter a number, -1 to stop : ");
int key;
do {
  key = scan.nextInt();
  int result = interpolationSearch(integerArray, key);
  if (result != -1) {
    System.out.println("\n"+ key +" element found at position "+ result);
  }
    break;
} while (key != -1);    // quit 
System.out.println("stop");
}
相关问题