Java: Can't access variable?
So i'm having a bit of a problem trying to compare two strings declared in the Main class. I've messed around with it and i really can't get it to work! The problem is in the if() statement where i compare the variables...
public class Main {
public String oldContent = "";
public String newContent = "";
publ开发者_如何学Goic 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.
}
}
the variables are instance members, whereas the for happens in a static method. try moving the actual function to an instance method (not static), or conversely make the data members static as well.
You may use name of the object you have created (downloadPage ) to access to the parameters: in the main finction use following instead of parameter names only:
downloadPage.oldContent
downloadPage.newContent
The variables are inside the Main
object:
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);
}
}
Do consider using getters and setters instead of exposing the fields.
See non static/ static variable error
精彩评论