Forums Register Login

problem declaring int x(int y) methods

+Pie Number of slices to send: Send
Hello

I'm doing a course in Java and I've got most of my program working, only there's one structure that won't work. I can't even get a listing from a book with a similar structure to work. Here's an example program:

public class Person
{
public static void main(String[] args)
{
int age;

int ageInNYears(int n)
{return age + n ;}
}
}

It always gives me the error message:
; expected
at the line:
int ageInNYears(int n)

I'm actually trying to get a different more complex program to work, but it's falling at the same place in the program - wherever I'm trying to create a method using int. I'm using JCreator. I've got other programs to compile just fine. It's just this construction that isn't working for me so far. I've tried adding in semi-colons all over the place and it's not working - I must be missing something more structural unrelated to this specific line where it fails.

It is completely doing my head in!

If anyone can shed any light on this, it would be most appreciated.

Thank you kindly!
+Pie Number of slices to send: Send
You're trying to declare the new method inside the body of the "main" method -- don't do that. Move your method outside of main, but inside the class.

Your next question will almost undoubtedly have to do with an error message involving the phrase "static context." The solution, at least for now, is to declare your new method static, the same way that "main" is declared static.
+Pie Number of slices to send: Send



I think you also need to add parentheses
to add n to age before you return anything.
(age + n )
+Pie Number of slices to send: Send
 

Originally posted by Elouise Kivineva:

I think you also need to add parentheses
to add n to age before you return anything.



No, that's not necessary.
+Pie Number of slices to send: Send
Thanks for your help! Ernest was right - the problem was that I had one method inside another method and declaring it as static and moving it to the right place did fix it.

Much appreciated - I've been able to get both that example program working okay and more importantly the real program I wanted to write working too. I was about to give up on Java altogether even though it's a really small thing, so now my faith is restored and I'll stick at it.

Have a great evening!

Sean
Doody calls. I would really rather that it didn't. Comfort me wise and sterile tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 774 times.
Similar Threads
exception in thread "main" error
[HELP]Trying to make a decision cmd adventure! How to branch decisions? NEED HELP AGAIN :S! NOT done
Classloading problem
Problem with Scanner input
For loop Pyramid Program
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 09:02:52.