Java:无法访问变量?
所以我在比较主类中声明的两个字符串时遇到了一点问题。我把它弄得一团糟,我真的无法让它工作!问题出在if()语句中,我在其中比较变量
public class Main {
public String oldContent = "";
public String newContent = "";
public static void main(String[] args) throws InterruptedException {
Main downloadPage = new Main();
downloadPage.downloadPage();
oldContent = newContent;
for (;;) {
downloadPage.downloadPage();
if (!oldContent.equals(newContent)) { // Problem
System.out.println("updated!");
break;
}
Thread.currentThread().sleep(3000);
}
}
private void downloadPage() {
// Code to download a page and put the content in newContent.
}
}
# 1 楼答案
变量位于
Main
对象内:请考虑使用GETSter和SETTER,而不是公开字段。
# 2 楼答案
您可以使用已创建对象的名称(downloadPage)访问以下参数: 在主函数中,仅使用以下名称而不是参数名称:
# 3 楼答案
见non static/ static variable error
# 4 楼答案
变量是实例成员,而for发生在静态方法中。 尝试将实际函数移动到实例方法(不是静态的),或者反过来使数据成员也是静态的