有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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.
    }
}

共 (4) 个答案

  1. # 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);
        }
    }
    

    请考虑使用GETSter和SETTER,而不是公开字段。

  2. # 2 楼答案

    您可以使用已创建对象的名称(downloadPage)访问以下参数: 在主函数中,仅使用以下名称而不是参数名称:

    downloadPage.oldContent
    downloadPage.newContent
    
  3. # 4 楼答案

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