Objective: Practice Catching Exceptions. The method isMilitaryTime accepts a Str
ID: 3729286 • Letter: O
Question
Objective: Practice Catching Exceptions. The method isMilitaryTime accepts a String time as a parameter and should return a true if the string is a valid time. Military Time Format is a 24hour clock. There are 4 digits. The first two digits are for the hour(00-23) and the last two digits are the minutes (00-59): Format: hhmm Times range from 0000 (midnight) to 2359 (11:59PM) but be careful. 2167 is an invalid time because the minutes are invalid Examples 12:00 AM: false 0000: true 1239:true 1300 true 1299 false 8815 false 7:05":false HHMM:taise (1 of 1: Tue Mar 13 2018 17:32:38 GMT-0400 (EDT) SUBMIT RESET 1 class ParseTime lie statie boolean iemilitaryTime(String time) boolean resultfalse return reaultExplanation / Answer
Please find my implementation.
public static boolean isMillitaryTime(String str) {
if(str == null || str.length() != 4)
return false;
String h = str.substring(0, 2);
String m = str.substring(2);
try{
int hour = Integer.parseInt(h);
int minute = Integer.parseInt(m);
if((hour >=0 && hour<=23) && (minute >=0 && minute <= 59))
return true;
return false;
}catch (Exception e) {
return false;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.