Search code examples
javaprogram-entry-pointmethod-call

Why doesn't my method return anything even though I have print statements?


When I attempt to call the daysInaMonth method in my main method, I get this error:

DaysInMonth.java:34: error: missing return statement
   }
   ^
1 error

What am I doing incorrectly? Why isn't the method call working? I've made sure that both methods return the correct data type. Here is my class file:

import java.util.Scanner;  
public class DaysInMonth { 

   public String daysInaMonth (int year_number, String month_name) {
      if(year_number % 4 != 0 || month_name != "February") {
         switch(month_name) {
            case "January":
            case "March":
            case "May":
            case "July":
            case "August":
            case "October":
            case "December":
                System.out.print("31");
               break;
            case "April":
            case "June":
            case "September":
            case "November":
                System.out.print("30");
               break;
            case "February":
               System.out.print("28");
               break;
            default:
               System.out.print("Please input ");
               break;
         }  
      }
      else {
           System.out.print("29");
      }

   }


   public String main(String[] args) {
   Scanner scnr = new Scanner(System.in);
   String month = " ";
   int year = 0;

   month = scnr.nextLine();

   year = scnr.nextInt();

   return daysInaMonth(year, month);


   }


}

Solution

  • The problem is that your daysInaMonth() method doesn't return anything. The signature says it should return a String.

    However, the method is currently setup to do printing, not to return Strings.

    First Option: Keep It as a Printing Method

    So, the easiest would be to change the signature of your method to:

    public void printDaysInAMonth (int year_number, String month_name) {
         // ... your code ...
    }
    

    Then, in main(), instead of doing:

    return System.out.print(daysInAMonth(year, month));
    

    Just do:

    printDaysInAMonth(year, month);
    

    Second Option: Return Something

    In daysInaMonth(), change every reference to System.out.print() to a return statement, to return the String. Also remove break, which will no longer be useful since you are returning. Example:

            case "December":
                return "31";
    

    Now in main(), you can call the daysInaMonth() and it will return the String value:

    String stringThatWeGotBack = daysInaMonth(year, month);
    System.out.println(stringThatWeGotBack);
    

    Or just:

    System.out.println(daysInaMonth(year, month));