Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Get more error in the below program

 
Rajesh Shekar
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
Im very new to java and i wrote a program as below and i get 4 errors not sure what they mean can someone help me?


MethodTest.java:6: ';' expected
int calcArea(int height,int width)
^
MethodTest.java:6: <identifier> expected
int calcArea(int height,int width)
^
MethodTest.java:6: not a statement
int calcArea(int height,int width)
^
MethodTest.java:6: ';' expected
int calcArea(int height,int width)
^
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're defining your function "calcArea" inside the definition of "main()". You can't do that -- you can't define one function inside of another one. Move the definition of "calcArea()" out to the class level -- i.e., before the "public static void main()" line:

 
Rajesh Shekar
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also i assume if i move the method outside main i need to create an object for the class "MethodTest" and call the calcArea method is that right?
 
Ryan Sykes
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rajesh Shekar wrote:Also i assume if i move the method outside main i need to create an object for the class "MethodTest" and call the calcArea method is that right?

Not if you declare the method to be static (which it should be in the case you listed above). A static method from within the same class can be called by its name alone, i.e. calcArea(w, h). If you are calling it from another class and if the function has the appropriate access modifier (eg: public), then you should call the static method by ClassName.staticmethodname(), i.e., MethodTest.calcArea(w, h). Note that this method call is not dependent on any instance of the MethodTest class.
 
Campbell Ritchie
Sheriff
Pie
Posts: 50208
79
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not convinced. It is a bad idea to make methods static until you really know what static means. It would be better to create a Square object, and call its calcArea() methodYou will obviously have to work out how to create your Rectangle class, with a constructor and fields.
 
Rajesh Shekar
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Both,
Thanks a lot i understood many things from this

1) Name a class properly.
2) use constructor with parameters (yet to learn this)
3) need to learn static.

Thanks a lot for helping me in this one.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic