sayid jetzenden sayid jetzenden - 4 months ago 8
Java Question

Java return a value from a method - beginner

I am really a beginner in Java and I would be grateful if someone could explaine me how can I get a return from my method in order to use it in another class from where I actually call the following one. My code is:

private static String[] months(int val){

String[] monthsNames = { "January", "February", "March", "April",
"May", "June", "July", "August", "September", "October",
"November", "December"};

return monthsNames[val];
}


edit: I did

public static String months(int val){

String[] monthsNames = { "January", "February", "March", "April",
"May", "June", "July", "August", "September", "October",
"November", "December"};

return monthsNames[val];
}


and what I get from eclipse is that monthsNames cannot be resolved to a variable

edit2**
now it works. Thanks everybody for your help!

Answer

You are returning one String, not a String[]. Change

private static String[] months(int val){

to

private static String months(int val){

But, if you want to call it from another class you will need to change private to public (or if the other class is in the same package, you could remove private and then you would have package-private level permission). Finally, if the other class is a sub-class, you might change private to protected (and then it is only visible to sub-classes).