I'm making this code for class but it will only display the number of days as 28 29 or 30. Im new to Java and would really appreciate help.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package days;

/**
 *
 * @author Curtie
 */import javax.swing.JOptionPane;
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        //Get user input
        String month = JOptionPane.showInputDialog("Enter the number of the month you want to know the days of.");
        String year = JOptionPane.showInputDialog("What year is your month in?");
       //Convert string to integer
        int years = Integer.parseInt(year);
        int months = Integer.parseInt(month);
       //Intitialize variable days
        int days = 0;
       //Code to determine if leap year for February
        if(months == 2){
           if((years % 4 == 0 && years % 100 != 0) || (years % 400 == 0)) days = 29;
           else days = 28;}
        if(months == 1) days = 31;
        if(months == 3) days = 31;
        if(months == 5) days = 31;
        if(months == 7) days = 31;
        if(months == 8) days = 31;
        if(months == 10) days = 31;
        if(months == 12) days = 31;
        else days = 30;
        JOptionPane.showMessageDialog(null, days);
                 
        
    }

}

have you noticed that the

else days = 30;

statement always runs.

you should use

break

statement after every

if

control.

in fact, its better if you use

switch

statement.

Hi,

1.

else days = 30;

runs only if months != 12

2. If you use break in your code, like:

if(months == 3) days = 31;
break; // the application ends here
if(months == 5) days = 31;

because break terminates the innermost block of code, which in your case is the main method. You should use break statement only in for, while, do and switch statements.

3. you can use the switch statement, like this:

switch (month) {
   case 1: case 3: case 5: case 7: case 8: case 10: case 12:
      numDays = 31;
      break;
   default:
      numDays = 30;
      break;

GL

This article has been dead for over six months. Start a new discussion instead.