QUESTION
- Create a new program called Time.java. From now on, I
won’t remind you to start with a small, working program, but you should.
- Following the example in Section 2.6, create variables
named hour, minute and second, and assign them values that are roughly the
current time. Use a 24-hour clock, so that at 2pm the value of hour is 14.
- Make the
program calculate and print the number of seconds since midnight.
- Make the
program calculate and print the number of seconds remaining in the day.
- Make the
program calculate and print the percentage of the day that has passed.
- Change the values of hour, minute and second to reflect
the current time (I assume that some time has elapsed), and check to make sure that
the program works correctly with different values.
The
point of this exercise is to use some of the arithmetic operations, and to
start thinking about compound entities like the time of day that that are
represented with multiple values. Also, you might run into problems computing
percentages with ints, which is the motivation for floating point numbers in
the next chapter.
HINT:
you may want to use additional variables to hold values temporarily
during the computation. Variables like this, that are used in a computation
but never printed, are sometimes called intermediate or temporary variables.
SOLUTION
public class ThinkJava2_Ex3 {
public static void main (String[]args) {
//Step 2
int hour, minute, second;
hour = 16;
minute = 24;
second = 39;
//For checking
System.out.println(hour+":"+minute+":"+second);
//Step 3
int secSinceMidNite;
secSinceMidNite = ((hour*60)+minute)*60 + second;
System.out.println("Seconds since midnight = "+secSinceMidNite);
//Step 4
int secRemainingInDay, totalSecInDay;
totalSecInDay = 24*60*60;
secRemainingInDay = totalSecInDay - secSinceMidNite;
System.out.println("Seconds remaining in day = "+secRemainingInDay);
//Step 5
int percentOfDayPassed;
percentOfDayPassed = (secSinceMidNite*100)/totalSecInDay;
System.out.println("Percentage of day passed = " +percentOfDayPassed+"%");
/*Step 6
Change values of hour, minute, second and run again
*/
}
}