Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that reads two times in military format (0900, 1730) and prints

ID: 3625538 • Letter: W

Question

Write a program that reads two times in military format (0900, 1730) and prints the number of hours and minutes between the two times. Here is a sample run. User input is in color.

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 the 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.

Here are sample program runs:

Please enter the first time:
0900
Please enter the second time:
1730
8 hours 30 minutes

Please enter the first time:
1730
Please enter the second time:
0900
15 hours 30 minutes
Your main class should be called ElapsedTimePrinter.

You need to supply the following class in your solution:

TimeInterval

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

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote