初学java,做个留念,根据网上的一些大牛的作品,理解,改了一些,实现了最后的程序…
import java.text.*; import java.util.Date; import java.text.ParseException; import java.util.Locale; public class shijian { public static void main(String[] args) { String times[] = {"15:20","27:10","16:78","abc","6:30"}; String line = null; for (String timeStr:times ) { System.out.println("==="); System.out.println("<<<TimeString for format converting in 24-hour notation is "+ timeStr); try { outTime(timeStr); //将24小时制转为12小时,如果有问题,就输出错误,只能判断时间是否超出范围和字符串中是否包含英文 } catch (TimeFormatException e) { } } System.out.println("End of program"); } public static void outTime(String line) throws TimeFormatException { SimpleDateFormat _24time = new SimpleDateFormat("HH:mm"); SimpleDateFormat _12time = new SimpleDateFormat("hh:mm a",Locale.ENGLISH); try { boolean a=is_alpha(line); if (a==true) { String s = "Time"; throw new TimeFormatException(s); } String[] array = line.split(":"); if (Integer.parseInt(array[0]) < 0 || Integer.parseInt(array[0]) > 23) { String s = "Hour"; throw new TimeFormatException(s); } if (Integer.parseInt(array[1]) < 0 || Integer.parseInt(array[1]) > 59) { String s = "Minute"; throw new TimeFormatException(s); } System.out.println(">>>Time in 12-hour notation is: " + _12time.format(_24time.parse(line))); } catch (Exception e) { } } public static boolean is_alpha(String str) { if(str==null) return false; return str.matches("[a-zA-Z]+"); } } class TimeFormatException extends Exception { public TimeFormatException(){} public TimeFormatException(String s){ System.out.println("TimeFormatException: Invalid Value for "+ s +"!"); } }