Labtest1
unknown
java
6 months ago
3.4 kB
6
Indexable
import java.util.Scanner; public class DateAnalyzer { // Method to determine the season based on the month and day public static String determineSeason(int month, int day) { if ((month == 3 && day >= 21) || (month >= 4 && month <= 5) || (month == 6 && day <= 20)) { return "Spring"; } else if ((month == 6 && day >= 21) || (month >= 7 && month <= 8) || (month == 9 && day <= 20)) { return "Summer"; } else if ((month == 9 && day >= 21) || (month >= 10 && month <= 11) || (month == 12 && day <= 20)) { return "Fall"; } else { return "Winter"; } } // Method to check if the date matches any holidays public static String checkHoliday(int month, int day) { if (month == 1 && day == 1) { return "New Year's Day"; } else if (month == 7 && day == 4) { return "Independence Day"; } else if (month == 12 && day == 25) { return "Christmas Day"; } else if (month == 10 && day == 31) { return "Halloween"; } else { return null; // No holiday on this date } } // Main method for user input and program logic public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Welcome to the Date Analyzer!"); System.out.println("Please enter a date in MM/DD format (e.g., 02/14):"); // Error handling for date input format boolean validInput = false; int month = 0; int day = 0; while (!validInput) { try { // Prompt user for input String input = scanner.nextLine(); String[] dateParts = input.split("/"); if (dateParts.length != 2) { throw new Exception("Invalid format"); } month = Integer.parseInt(dateParts[0]); day = Integer.parseInt(dateParts[1]); // Validate month and day ranges if (month < 1 || month > 12 || day < 1 || day > 31) { throw new Exception("Month or day is out of range."); } // Check for invalid day numbers based on month (e.g., Feb 30 is invalid) if ((month == 2 && day > 29) || ((month == 4 || month == 6 || month == 9 || month == 11) && day > 30)) { throw new Exception("Invalid day for the given month."); } validInput = true; // If no exception, input is valid } catch (Exception e) { // Display error message and prompt user again System.out.println("Invalid input. Please enter the date in MM/DD format (e.g., 02/14):"); } } // Determine the season for the given date String season = determineSeason(month, day); // Check if the date is a holiday String holiday = checkHoliday(month, day); // Output the results to the user System.out.println("The date " + month + "/" + day + " falls in " + season + "."); if (holiday != null) { System.out.println("This date is also " + holiday + "!"); } else { System.out.println("There are no major holidays on this date."); } scanner.close(); // Close the scanner } }
Editor is loading...
Leave a Comment