Click to See Complete Forum and Search --> : newbie -- variables question
Znupi
11-20-2007, 12:59 PM
Ok I just started learning Java. I'm using this tutorial: http://java.about.com/od/beginningjava/a/beginjavatutor.htm and using Eclipse as my IDE. Now, I tried this simple code:
public class HelloWorld {
private int somevar = 5;
public static void main(String[] args) {
System.out.print(somevar);
}
}
but I get this error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Cannot make a static reference to the non-static field somevar
it works if I delcare somevar like this: "private static int somevar = 5;". But I don't want it to be static. Help please :(
jasonahoule
11-20-2007, 01:07 PM
It is because you are trying to access it from a static method. You can do one of two things here. One is to declare your variable in the method. Two, you can make the variable static. Why do you not want it to be static? If that is really the case then you most likely should not be declaring this variable in your entrypoint class.
Znupi
11-20-2007, 01:53 PM
Well, I'm very familiar with PHP and I'm trying to translate this:
class HelloWorld {
var $myvar;
function HelloWorld($newvar) {
$this->myvar = $newvar;
}
function printVar() {
echo $this->myvar;
}
}
$hc1 = new HelloWorld(5);
$hc2 = new HelloWorld(2);
$hc1->printVar();
$hc2->printVar();
into Java, so I tried this:
HelloWorld.java
import "HelperClass.java";
public class HelloWorld {
public static void main(String[] args) { // Line 5 :(
HelperClass hc1 = new HelperClass(5);
HelperClass hc2 = new HelperClass(2);
hc1.printVar();
hc2.printVar();
}
}
HelperClass.java
public class HelperClass {
private int myvar;
public HelperClass(int newvar) {
myvar = newvar;
}
public void printVar() {
System.out.print(myvar + "\n");
}
}
But the compiler throws this error:
xception in thread "main" java.lang.Error: Unresolved compilation problem:
at HelloWorld.main(HelloWorld.java:5)
And also eclipse says there's an error on line one in HelloWorld.java:
Syntax error on token ""HelperClass.java"", Identifier expected
It seems I'm not really a fast learner :( please help, I don't understand why this isn't working :(
jasonahoule
11-20-2007, 03:32 PM
In Java you do not need the .java on your import. In fact, you absolutely need to get rid of because the compiled code will reference HelperClass.class. Also, there should not be any quotes around the imported file and it should be prefixed by the package unless it lives in the same package which in that case you do not need to import it at all.
Znupi
11-20-2007, 03:52 PM
Thank you. It works now :)
jasonahoule
11-20-2007, 03:54 PM
No problem. Java can be tough to grasp at first. I, like you, came from a PHP background so I know what you are going through.