P4.15)Write a program that reads two times in military format (eg. 0900, 1730) a
ID: 3650379 • Letter: P
Question
P4.15)Write a program that reads two times in military format (eg. 0900, 1730) and prints the number of hours and minutes between the two times. Here is a sample run.Please enter the first time: 0900
Please enter the second time: 1730
8 hours 30 minutes
Extra credit if you can deal with the case where the first time is later than the second:
Please enter first time: 1730
Please enter the second time: 0900
15 hours 30 minutes
Implement a class TimeInterval whose constructor takes two military times. The class should have two methods getHours and getMinutes.
Explanation / Answer
ElapsedTimePrinter.java
import java.util.*;
public class ElapsedTimePrinter {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please enter the first time: ");
int t1 = in.nextInt();
System.out.print("Please enter the second time: ");
int t2 = in.nextInt();
TimeInterval ti = new TimeInterval(t1,t2);
System.out.println(ti.getHours()+" hours "+ti.getMinutes()+" minutes");
}
}
--------------------------------------------
TimeInterval.java
public class TimeInterval {
int timeDiff; // difference between the two times, in minutes
public TimeInterval(int t1, int t2) {
timeDiff = timeInMinutes(t2)-timeInMinutes(t1);
if (timeDiff < 0)
timeDiff = timeDiff + (60*24); // This handles the case where t2 is earlier than t1
}
// Given a military-format time, returns the number of minutes since midnight
private int timeInMinutes(int t) {
return (t/100)*60 + (t%100);
}
public int getHours() {
return timeDiff / 60;
}
public int getMinutes() {
return timeDiff %60;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.