Java

OOP GUIDE / WORK

 

DURATION CLASS SOLUTIONS

 

 

TASK – PART 1 – DURATION CLASS

 

public class Duration

{

     private int hours;

     private int minutes;

     private int seconds;

    

     public Duration(int h, int m, int s)

     {

           hours = h;

           minutes = m;

           seconds = s;

     }

    

     public Duration(int m, int s)

     {

           hours = 0;

           minutes = m;

           seconds = s;

     }

    

     public Duration(int s)

     {

           hours = 0;

           minutes = 0;

           seconds = s;

     }

    

     public int getTotalSeconds()

     {

           return hours * 3600 + minutes * 60 + seconds;

     }

    

     public String toString()

     {

           return hours + "h" + minutes + "m" + seconds + "s";

     }

}

 

 

TASK – PART 2 – TESTING THE DURATION CLASS

 

Here is my solution:

 

 

public class DurationTester

{

     public static void main(String[] args)

     {

           Duration starWarsMovie = new Duration(2, 1, 0);

           System.out.println(starWarsMovie);

           System.out.println(starWarsMovie.getTotalSeconds() + " seconds");

          

           Duration sagaBeginsSong = new Duration(5, 37);

           System.out.println(sagaBeginsSong);

           System.out.println(sagaBeginsSong.getTotalSeconds() + " seconds");

 

           Duration yodaSong = new Duration(238);

           System.out.println(yodaSong);

           System.out.println(yodaSong.getTotalSeconds() + " seconds");

     }

}

 

 

The above will output:

 

2h1m0s

7260 seconds

0h5m37s

337 seconds

0h0m238s

238 seconds

 

 

TASK – PART 3 – SHORT ANSWER QUESTIONS

 

a)    Constructor #2 (and Constructor #3) can be accidentally misused.  Can you predict how a programmer might make an error?

ANSWER

One can easily think that the constructor with two integers is designed to take an amount of hours and minutes instead of an amount of minutes and seconds.  This is particularly true if you are working with durations of movies where seconds are not used. 



b)    The method getTotalSeconds() requires a calculation that might be challenging for some.  How would you test it to make sure that is working correctly like it is intended to be?

ANSWER

The key is to create many different duration objects with a good variety of values of hours, minutes and seconds.  TO start, one can create the duration with 1 hour, 0 minutes and 0 seconds and make sure that that total seconds is 3600.  Then, a duration of 2 hours, 0 minutes and 0 seconds and make sure that the total seconds is 7200.  Then, one can start adding minutes and seconds.