Java Tutorial #5 — Calculating seconds


Topics Discussed: Using what we’ve learned so far to calculate how many seconds are in a user-defined amount of time

Source Code Available Here

In this lesson I show you guys the power of using compound operators, as well as including a good amount of variables in a single print statement.
Compound operators
Throughout this lesson I combine a lot of statements in order to avoid using a ‘total’ variable, here’s the example:


       hours += (days*24); //line 1
       minutes += (hours*60);// line 2
       seconds += (minutes*60); // line 3

These three lines do the following things:
Line 1: Starts by taking the current value of hours and adds the value of days * 24 (meaning that days * 24 = number of hours in a day). So in one statement we count the number of hours in a day, and add that value to days
Line 2: Like the above, we are converting “downward”. We multiply hours by 60 and add the total to minutes. For reference this adds the amount of hours in days, and the amount of hours we had to begin with
Line 3: Similarly to the lines above, this takes minutes and converts / adds them to seconds.


Without compound statements the code would look something like this:


       days = days * 24;
       hours= hours + days;
       hours = hours *24;
       minutes = hours + minutes;
       minutes = minutes * 60;
       seconds = seconds + minutes;


Maximum combination
As you can see the above doesn’t do anything to help us out. There is another way we could have done this… but it’s a bit more contrived. With a little bit of our calculator we can learn that there are 86,400 seconds in a day, 3600 seconds in an hour, and 60 seconds in a minute. Thus we can get rid of everything but the println statement.


System.out.println("The number of seconds in " + days + " days " + hours + " hours " + minutes + " minutes and " 
+ seconds + " seconds is: " + ((days*86400)+(hours*3600)+(minutes*60)+seconds));

This sort of coding is technically proper, but can be confusing when you’re using more complex variables, so it’s generally avoided.


Using a total variable
Although I avoided using one here, there are times where it will be inappropriate to change the values of variables so we’ll declare a total variable to hold all of our variables. The code would to use a total variable in place of our existing variables would look like this:


       total += (days*86400);
       total += (hours*3600);
       total += (minutes*60);
       total += seconds;

You’ll notice that instead of using our existing variables we use total to hold the value of each converted variable.

Leave a Reply

Your email address will not be published. Required fields are marked *