Time class creating normal time (12 hour clock)

// jamesprogram.java
class jamesprogram {

	public static void main (String[] args){
		
		// make a cat object to we can use the methods
		// within the cat class
		cat catObject = new cat();
		catObject.makeTime(14,15,20);	
		System.out.println(catObject.militaryTime());
			
		System.out.println(catObject.toString());
		
	}
}
//cat.java
public class cat {

	private int hour;
	private int minute;
	private int second;
	
	public void makeTime (int h, int m, int s){
		// check data inputed is right
		hour = ((h>=0 && h<24)? h : 0);
		minute = ((m>=0 && m<60)? m : 0);
		second = ((s>=0 && s<60)? s : 0);
	}
	
	// display through military time 12 to 24
	public String militaryTime(){
		// display first one to two decimal places
		// add a colon, display second one to two
		// decimal places (the 02d bit means to
		// two desimal places
		return String.format("%02d:%02d:%02d", hour, minute, second);
	}
	
	public String toString(){
		return String.format("%d:%02d:%02d %s", ((hour==0||hour==12)?12:hour%12),minute,second,(hour<12?"am":"pm"));
		
	}
}

Outputs:

14:15:20
2:15:20 pm

Leave a Reply