Question
import java.util.*; public class Project4 { public static void main(String[] args) { String again = ; do { Scanner keyboard = new Scanner(System.in); System.out.println(Enter the
import java.util.*; public class Project4 { public static void main(String[] args) { String again = ""; do { Scanner keyboard = new Scanner(System.in); System.out.println("Enter the 24 hour format time: "); String time = keyboard.next(); if(time.indexOf(":") == -1 ) { System.out.println("Invalid Input. Time must be in format of HH:MM"); } else { try { int hours =Integer.parseInt(time.substring(0,time.indexOf(":"))); int minutes =Integer.parseInt(time.substring(time.indexOf(":")+1, time.length())); if(minutes < 00 || minutes > 59) { throw new TimeFormatException(); } else if(hours < 0 || hours > 23) { throw new TimeFormatException(); } else { String smin = "00"; String shours = "12"; String s = "AM"; if(hours == 12 && minutes == 0) { s = "PM"; System.out.println(hours+":"+smin+" "+ s); } else if(hours == 12 ) { s = "PM"; System.out.println(hours+":"+minutes+" "+ s); } else if(hours == 0 && minutes == 00) { System.out.println(shours+":"+smin+" "+ s); } else if(hours == 0) { System.out.println(shours+":"+minutes+" "+ s); } else if(hours>11 && minutes == 0) { s = "PM"; hours = hours - 12; System.out.println(hours+":"+smin+" "+ s); } else if(hours>11) { s = "PM"; hours = hours - 12; System.out.println(hours+":"+minutes+" "+ s); } else if(minutes == 0) { System.out.println(hours+":"+smin+" "+ s); } else { System.out.println(hours+":"+minutes+" "+ s); } } } catch(Exception e) { System.out.println("Invalid Input. Try again"); } System.out.println("again? y/n"); again = keyboard.next(); } } while(again.equalsIgnoreCase("Y")); System.out.println("Program is exiting"); } }
I have this code that is supposed to change time from a 24 hour format to a 12 hour format. I am having a hard time getting it to throw an exception for if the minutes are less than 2 digits. Any help would be appreciated, thanks!
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started