将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);
	}


	@Override
	public 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);
		}
	}

你可能感兴趣的:(正则表达式)