This is a programming project from a textbook, and it executes as intended. However, I can't help but thinking there are ways to simplify the code because the if statement I am using is massive, with nested if statements inside.
Any ideas on simplifying this code? Or any ideas on alternatives to the if statement I am using?
(The program is to convert 24-hour time into 12-hour time, and the jpb package is needed to use the SimpleIO class.)
// the jpb package needed to use the SimpleIO class import jpb.*; public class equivalent12HourTime { public static void main(String[] args) { // hh:mm user input SimpleIO.prompt("\nEnter a 24-hour time\n in military hh:mm format\n (example: 21:11 --> 11:11 p.m.) : "); String hh_mm = SimpleIO.readLine(); // int hour String hh = hh_mm.substring(0, 2); int hour = Integer.parseInt(hh); // int minutes String mm = hh_mm.substring(3); int minutes = Integer.parseInt(mm); /* ginormous nested if statement: 1. checks minutes for errors, 2. checks hours for errors, 3. converts 24-hour into 12-hour format and prints */ if ( (minutes <= 0) || (minutes >= 60) ) { System.out.println("\nIncorrect time entered, please try again."); } else { if ( (hour > 0) && (hour <= 12) ) { if (hour == 12) { System.out.println("\nEquivalent 12-hour time: " + hour + ":" + minutes + " p.m."); } else { System.out.println("\nEquivalent 12-hour time: " + hour + ":" + minutes + " a.m."); } } else if ( (hour > 12) && (hour <= 24) ) { if (hour == 24) { System.out.println("\nEquivalent 12-hour time: " + (hour - 12) + ":" + minutes + " a.m."); } else { System.out.println("\nEquivalent 12-hour time: " + (hour - 12) + ":" + minutes + " p.m."); } } else { System.out.println("\nIncorrect time entered, please try again."); } } // end of if statement } }