Click to See Complete Forum and Search --> : Error help on println
JMaia
April 8th, 2010, 05:46 PM
Hi, I started studying java on my own a few days back. Anyway, can plase someone tell me what is wrong with this piece of code?:
public class bananas {
int width =2 , height = 5;
int area = getArea() ;
System.out.println("The area is " + area);
int getArea (){
return (width * height);
}
}
Eclipse says - Syntax error on token "println", = expected after
this token
- Syntax error on token(s), misplaced construct(s)
Thanks for the help
dlorde
April 9th, 2010, 07:07 AM
The println call is in class scope (i.e. in the class body) instead of in method scope (i.e. inside a method). In general, you can only put variable and method declarations in the class body. Other code must go inside methods.
Incidentally, the Java naming convention is for class names to start with an uppercase letter and method & variable names to start with a lowercase letter.
Programs must be written for people to read, and only incidentally for machines to execute...
H. Abelson and G. Sussman
JMaia
April 9th, 2010, 11:27 AM
So I have to put the println inside braces? I tried to do that and the error did go away, but when I try to run the program (like it is presented below) it gives another error: java.lang.NoSuchMethodError: main
Exception in thread "main"
public class bananas {
int width =2 , height = 5;
int area = getArea() ;
{
System.out.println("The area is " + area);
}
int getArea (){
return (width * height);
}
}
dlorde
April 9th, 2010, 02:02 PM
So I have to put the println inside braces?
No, it must go inside a method, like all executable code.
when I try to run the program (like it is presented below) it gives another error: java.lang.NoSuchMethodError: main
That's because to execute a class, the Java runtime looks for a method called 'main'. The 'main' method is known as the 'entry point' because it tells the Java runtime where to start executing the code.
This is really basic Java knowledge. I strongly recommend that you take a Java course, read a Java book (http://www.codeguru.com/java/tij/), or take an online tutorial (http://java.sun.com/docs/books/tutorial/index.html) - at least. Most of us are here to help people solve their Java problems, not to teach Java - there are much better & quicker ways of learning Java than a forum.
If you get stuck on something, or don't understand something, you're welcome to ask.
If I had eight hours to chop down a tree, I would spend 6 hours sharpening an axe...
Anon.
keang
April 9th, 2010, 02:05 PM
If you want a class to be executable you need to declare a main method, which is the entry point for the application. The main method is declared as follows:
public static void main(String[] args)
{
... Your Code Here ...
}
Where 'args' is the command line arguments, if any are provided.
JMaia
April 9th, 2010, 08:17 PM
Thanks for the help I think I got it now.
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.