How to write a Java program to calculate the number of days in the corresponding month using switch structure
This article mainly explains "how to write Java programs to use switch structure to calculate the number of days of the corresponding month", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "how to write Java programs to use switch structure to calculate the number of days of the corresponding month"!
The questions are as follows:
Write a Java program, enter the year and month, and use the switch structure to calculate the number of days of the corresponding month.
The month is 1, 3, 5, 7, 8, 10, 12:00, and the number of days is 31 days.
The month is 4, 6, 9, 11:00, and the number of days is 30 days.
The month is 2 hours, if it is a leap year, the number of days is 29 days, otherwise, the number of days is 28 days.
Implement the following programs:
Use the switch statement to implement the code package rjxy2019_java_demo;import java.util.Scanner;public class SwitchWithDays {public static void main (String [] args) {Scanner input = new Scanner (System.in); System.out.println ("Please enter a year:"); int year = input.nextInt (); System.out.println ("Please enter a month:"); int month = input.nextInt (); int day = 0 Boolean isLeapYear = ((year% 4 = = 0 & & year% 100! = 0) | | (year% 400 = = 0)); switch (month) {case 1:case 3:case 5:case 7:case 8:case 10:case 12:day = 31 2:if 2:if (isLeapYear = = true) day = 29else day = 28 break defaultyear system. Out.println ("Error:invalid input"); System.exit (1) } System.out.println (year + "year" + month + "month total" + day + "day");}}
Validate, when input is February 2009:
Second, rewrite the code back to if else's optional structure package rjxy2019_java_demo;import java.util.Scanner;public class IfElseWithDays {public static void main (String [] args) {Scanner input = new Scanner (System.in); System.out.println ("Please enter a year:"); int year = input.nextInt (); System.out.println ("Please enter a month:"); int month = input.nextInt () Int day = 0 Boolean isLeapYear = ((year% 4 = = 0 & & year% 100! = 0) | | (year% 400 = = 0); if (month = = 1 | | month = = 3 | month = = 5 | month = = 7 | | month = = 8 | | month = = 10 | | month = = 12) day = 31 else {if (month = 4 | | month = 6 | | month = = 9 | month = = 11) day = 30 if {if (month = 2) {if (isLeapYear = = true) day = 29th day = 28) } else {System.out.println ("Error:invalid input"); System.exit (1);}} System.out.println (year + "year" + month + "month total" + day + "day") }} at this point, I believe you have a deeper understanding of "how to write Java programs to use switch structure to calculate the number of days of the corresponding month". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!