首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

将24小时制的时间转换成12小时制,练习自定义错误处理和简单的正则表达式

2012-12-19 
将24小时制的时间转换成12小时制,练习自定义异常处理和简单的正则表达式在异常处理的方面还需要进一步的加

将24小时制的时间转换成12小时制,练习自定义异常处理和简单的正则表达式
在异常处理的方面还需要进一步的加强和改善,下一步应该加强对正则表达式的使用。

package com.cn.tibco.time;import java.util.Scanner;public class GetTime {public static void main(String args[]) {GetTime getTime = new GetTime();boolean ison = true;while (ison) {getTime.resetTime();System.out.println("Again?(y/n)");Scanner keyboard = new Scanner(System.in);String yn = keyboard.next();if (yn.equalsIgnoreCase("n")) {ison = false;}}}public void resetTime() {System.out.println("Enter time in 24-hour notation:");Scanner keyboard = new Scanner(System.in);String time = keyboard.nextLine();System.out.println("That is the same as");try {isFormat(time);int hours = getHours(time);int minutes = getMinutes(time);if (hours > 12 && minutes >9) {String h1 = Integer.valueOf(hours - 12).toString();time = h1 + ":" + getMinutes(time) ;System.out.println(time + " pm");} else if ( hours > 12 && minutes <10) {String h1 = Integer.valueOf(hours - 12).toString();time = h1 + ":0" + getMinutes(time) ;System.out.println(time + " pm");}else {System.out.println(time + " am");}} catch (TimeFormatException e) {e.printStackTrace();resetTime();}}//检验时间格式,还需要进一步加强格式的处理。public void isFormat(String time) throws TimeFormatException {        if(!time.contains(":")){throw new TimeFormatException("There is no such time as " + time);}int hours = getHours(time);int minutes = getMinutes(time);if (hours < 0 || hours > 24) {throw new TimeFormatException("There is no such time as " + time);} else if (minutes < 0 || minutes > 59) {throw new TimeFormatException("There is no such time as " + time);}}//得到小时数public int getHours(String time) {int pos;pos = time.indexOf(":");int hours = Integer.parseInt(time.substring(0, pos));return hours;}//得到分钟数public int getMinutes(String time) {int pos;pos = time.indexOf(":");int minutes = Integer.parseInt(time.substring(pos + 1));return minutes;}}


异常处理类
package com.cn.tibco.time;public class TimeFormatException extends Exception {public TimeFormatException(){super();}public TimeFormatException(String message){super(message);}@Overridepublic String getMessage() {return super.getMessage();}}






//使用正则表达式对方法isFormat()进行修正,代码如下:
public void isFormat(String time) throws TimeFormatException {        if(!time.matches("\\d{1,2}\\:\\d{2}")){throw new TimeFormatException("There is no such time as " + time);}int hours = getHours(time);int minutes = getMinutes(time);if (hours < 0 || hours > 24) {throw new TimeFormatException("There is no such time as " + time);} else if (minutes < 0 || minutes > 59) {throw new TimeFormatException("There is no such time as " + time);}}

1 楼 mfkvfn 2012-09-12   你这也太...
用SimpleDateFormat类先用HH:mm:ss来parese一下时间,然后用hh:mm:ss a来format一下不就行了。 2 楼 haohao-xuexi02 2012-09-17   重新封装下。。。如楼上所说。。有封装好的方法 。。直接调用。。即可。。

热点排行