Saturday, February 13, 2016

Exercise 2.3

QUESTION

  1. 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.
  2. 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.
  3. Make the program calculate and print the number of seconds since midnight.
  4. Make the program calculate and print the number of seconds remaining in the day.
  5. Make the program calculate and print the percentage of the day that has passed.
  6. 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
*/
}
}

3 comments:

  1. hi! thanks for replying =) I don't really understand how is Step 6 incorrect because it just involves changing the values of hour, minute and second to run the code again.

    Can you elaborate on that?

    ReplyDelete
  2. Hi Johny, the correct task for step 6 is: "Change the values of hour, minute, and second to reflect the current time. Then
    write code to compute the elapsed time since you started working on this exercise."
    Plz email me on s.naidu2009@gmail.com if u hv the proper solution, wud appreciate a lot.

    ReplyDelete