找不到类或变量

  • 本文关键字:变量 找不到 java
  • 更新时间 :
  • 英文 :


我使用解释Java进行web抓取,不确定我最近在PC上升级到Java(版本8.x而不是版本7.x)是否与我的问题有关,但我不能再在if语句中声明字符串,然后在外部调用它。这以前是有效的,但现在不行了。有问题的代码是这样的:

if (tmp.indexOf("<b>") >= 0) {
    String[] stockSPLIT = tmp.split("<b>"); 
}

然后再往下看我使用的代码:

if (stockSPLIT.length > 2)

我已经找到了通过在页面顶部使用以下代码来修复它的方法,但不知道是否有人能为我指明正确的方向,说明为什么这种方法曾经有效?

String[] stockSPLIT = {"",""};

如果它有效,那么旧的功能实际上是不正确的。变量可达性受其范围的限制:

if (...)
{ // new scope
    String[] stockSPLIT = ...;
} // scope ends, all variables declared inside it are now unreachable

您的修复也不能正常工作,因为它没有使用旧的变量,而是创建了一个新的、完全不同的变量,而这个变量恰好具有相同的名称。正确的解决方案是:

String[] stockSPLIT = {};
if (...) {
    stockSPLIT = ...; // no String[] here
}
if (stockSPLIT.length > 2)

您并没有真正修复它,该变量仅在其定义的范围内是已知的-两个stockSPLIT根本不相关,每个都指向不同的变量。

if(something) {
   String tmp = "Hi";
}
//tmp is not accessible here
if(somethingElse) {
   String tmp = "Bye";
   //tmp is a different variable, not related to the previous one
}

当你有

String[] stockSPLIT = {"",""};

正如您所提到的,在"页面顶部",您正在创建一个成员变量,该变量可通过类访问。请注意,"页面顶部"不是它工作的原因,您也可以在任何方法之外的页面底部替换它。

最新更新