Java:无法访问变量?

时间:2011-04-16 16:27:54

标签: java variables

所以我在尝试比较Main类中声明的两个字符串时遇到了一些问题。我搞砸了它,我真的无法让它工作!问题出在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.
    }
}

4 个答案:

答案 0 :(得分:3)

变量是实例成员,而for在静态方法中发生。 尝试将实际函数移动到实例方法(不是静态),或相反地使数据成员也是静态的。

答案 1 :(得分:2)

您可以使用您创建的对象的名称(downloadPage)来访问参数: 在主要功能中使用以下代替仅参数名称:

downloadPage.oldContent
downloadPage.newContent

答案 2 :(得分:1)

变量位于Main对象中:

public static void main(String[] args) throws InterruptedException {
    Main downloadPage = new Main();
    downloadPage.downloadPage();  // Access them like you accessed the method
    downloadPage.oldContent = downloadPage.newContent;

    for (;;) {
        downloadPage.downloadPage();
        if (!downloadPage.oldContent.equals(downloadPage.newContent)) {
            System.out.println("updated!");
            break;
        }
        Thread.currentThread().sleep(3000);
    }
}

请考虑使用getter和setter而不是公开字段。

答案 3 :(得分:0)