How to output a date using a switch statement with nested if-else statements

后端 未结 1 1492
温柔的废话
温柔的废话 2020-12-22 10:58

Hi this is my code that I have used for my application. Every thing works fine however in some instances when inputting data that would use case 2 the if-else statement and

相关标签:
1条回答
  • 2020-12-22 11:30

    You're missing break in all your cases. Due to that, the switch falls through, and all the cases are executed. Insert break at appropriate places:

    switch (month) {  
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                if (day > 31)
                    System.out.print(date + " is an invalid date.");
                else 
                    System.out.print(date +  " is a valid date.");
                break;  // Here
    
            case 4:
            case 6:
            case 9:
            case 11:
                if (day > 30)
                    System.out.print(date + " is an invalid date.");
                else 
                    System.out.print(date +  " is a valid date.");
                break;  // Here
    
            case 2:
                if (year % 4 == 0)
                    if (day > 29)
                       System.out.print(date + " is an invalid day.");
                    else
                       System.out.print(date + " is a valid date and leap year.");
                else
                    if (day > 28)
                        System.out.print(date + " is an invalid day.");
                    else
                       System.out.print(date + " is a valid date.");
                break;  // Here
    
            default:
                System.out.println("The date: " + date + " has an invalid month");
    
        }       
    

    And please make a habbit of always enclosing your ifs and elses with curly braces.

    0 讨论(0)
提交回复
热议问题