Java Online Compiler
Example: DaysInMonth in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// DaysInMonth import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { // Step 1: Create a Scanner object to read user input Scanner scanner = new Scanner(System.in); // Step 2: Prompt the user to enter the month (1-12) System.out.print("Enter the month (1-12): "); int month = scanner.nextInt(); // Step 3: Prompt the user to enter the year System.out.print("Enter the year: "); int year = scanner.nextInt(); // Step 4: Declare a variable to store the number of days int numberOfDays = 0; // Step 5: Use a switch statement to determine days based on month switch (month) { case 1: // January case 3: // March case 5: // May case 7: // July case 8: // August case 10: // October case 12: // December numberOfDays = 31; break; case 4: // April case 6: // June case 9: // September case 11: // November numberOfDays = 30; break; case 2: // February // Check for leap year if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) { numberOfDays = 29; // Leap year } else { numberOfDays = 28; // Common year } break; default: System.out.println("Invalid month entered."); return; // Exit the program if month is invalid } // Step 6: Display the result if (numberOfDays != 0) { System.out.println("Number of days in " + getMonthName(month) + " " + year + ": " + numberOfDays); } // Step 7: Close the scanner scanner.close(); } // Helper method to get month name (optional, for better output) public static String getMonthName(int month) { String[] monthNames = {"", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; if (month >= 1 && month <= 12) { return monthNames[month]; } return "Invalid Month"; } }
Output
Clear
ADVERTISEMENTS