Re: get error on System.println.....
Eric Sosman wrote:
maya wrote:
hi,
I'm trying to write a simple class.. get error on System.out.println :
public class Circle {
double radius = 1.0;
double PI = 3.14159;
double result = area(radius);
String res = Double.toString(result);
System.out.println(res); // why do I get an error on this line?
// identifier expected
Executable statements (like this method call) must be inside
methods or constructors or initializer blocks; they can't just
float around in the class.
It may appear to you that the four preceding lines are also
"executable statements," and it's true that they call for some
code to get executed. But in truth they're "declarations" that
happen to have initializers. Behind the scenes, Java actually
moves the initializing code into the class' constructors so it
will be executed whenever a Circle object is built. It's a
convenience specifically for initializers -- but it doesn't
extend as far as allowing arbitrary code outside methods, etc.
thank you very much Eric... I put that stmt inside 'main' method, but I now I get
the "non-static variable... cannot be referenced.." error... (I have read up on
this error again and again, but I always forget after a while, what it's about
exactly.. what a pain..) thank you...
double radius = 1.0;
double PI = 3.14159;
double result = area(radius);
String res = Double.toString(result);
public static void main (String[] args) {
System.out.println(res);
}
double area(double radius) {
return PI * radius * radius;
}