Erin
Erin

Reputation: 29

Why won't my method return anything?

Here is my code, when I go to compile and run the code, it returns nothing which I don't understand because I have return statements in the If and the Else.

public class Program8
{
    public static void main(String[] args)
    {
        getMonth("02/12/96");
    }

    public static int getMonth(String date)
    {
        if(date.substring(0,1).equals("0")) 
        {
            return Integer.parseInt(date.substring(1,2));
        }
        else 
        {
            return Integer.parseInt(date.substring(0,2));
        }
    }
}

Upvotes: 2

Views: 60

Answers (3)

Alex Shesterov
Alex Shesterov

Reputation: 27585

Your method getMonth does return a value, but it is just discarded in the main method.

Probably you wanted to print it, like this:

public static void main(String[] args){
    System.out.println(getMonth("02/12/96"));
}

Or log it, or out make it somehow visible to the user (e.g. GUI), or assign it to a variable like this:

public static void main(String[] args){
    int month = getMonth("02/12/96"); 
    // now `month` can be used for the subsequent operations/calculations
}

and then use the variable value in further calculations.

Upvotes: 4

user2390182
user2390182

Reputation: 73498

You are not outputting anything. Try:

public static void main(String[] args){
    System.out.println(getMonth("02/12/96"));
}

Upvotes: 2

Mathisca
Mathisca

Reputation: 54

You need to print the returned variable to the console.

e.g.

public static void main(String[] args){
    System.out.println(getMonth("02/12/96"));
}

The programm can't know if you want to print the month in the console.

Upvotes: 1

Related Questions