sayid jetzenden
sayid jetzenden

Reputation: 153

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!

Upvotes: 2

Views: 96

Answers (4)

GhostDede
GhostDede

Reputation: 446

Making the method private restricts the visibility to the class in which the method is declared. If you want to use this method in another class you should make it more visible, for example by declaring it public.

Secondly your method is currently returning an array of String (String[]). If you want to return a String you should use public static String months(int val) instead of public static String[] months(int val)

If the method returned the monthsNames variable, String[] would be correct, however the elements of monthsNames are just String.

public static String months(int val) {
    String[] monthsNames = { "January", "February", "March", "April", 
            "May", "June", "July", "August", "September", "October", 
            "November", "December"};
    return monthsNames[val];
}

Upvotes: 4

shi
shi

Reputation: 511

If you want to return months Name from monthsNames just change the return type and access modifier.

private static String[] months(int val); 

to

public static String months(int val);

Upvotes: 2

Change the return type, you want to return the string when given the index...

private static String months(int val){..

Upvotes: 2

Elliott Frisch
Elliott Frisch

Reputation: 201399

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).

Upvotes: 4

Related Questions