Objective: Practice Catching Exceptions. The method isStandardTime accepts a Str
ID: 3729282 • Letter: O
Question
Objective: Practice Catching Exceptions. The method isStandardTime accepts a String time as a parameter and should return a true if the string is a valid time. Standard Time is a time format using a 12-hour clock: h:mm[SPACE][AIP]M Times range from 12:00 AM (midnight) to 11:59PM Examples: 12:00 AM:true 9:30 AM: true 12:00 PM: true 12:99 AM" false 13:00 PM" false 7:05" : false 1 of 1: Tue Mar SUBMIT RESET 1 class ParseTime public static boolean isstandardrime (String time) boolean result false; return result; 10Explanation / Answer
Please find my answer.
public static boolean isStandardTime(String str) {
if(str == null || str.length() < 7)
return false;
int indexColon = str.indexOf(':');
if(indexColon < 0)
return false;
String h = str.substring(0, indexColon);
int indexSpace = str.indexOf(' ');
String m = str.substring(indexColon+1, indexSpace);
String tt = str.substring(indexSpace+1);
try{
int hour = Integer.parseInt(h);
int minute = Integer.parseInt(m);
if(minute < 0 || minute > 59 || hour < 0 || hour > 12)
return false;
if(!("am".equalsIgnoreCase(tt) || "pm".equalsIgnoreCase(tt)))
return false;
return true;
}catch (Exception e) {
return false;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.