nemorathwald: (Default)
nemorathwald ([personal profile] nemorathwald) wrote2009-01-15 01:21 pm
Entry tags:

Java Homework Number One, Part One

Write an application that reads a value representing a number of seconds, then print the equivalent amount of time as a combination of hours, minutes and seconds. For example, 9999 seconds is equivalent to 2 hours, 46 minutes, and 39 seconds.

Here is my solution.

// Import the Scanner class to receive console input.
import java.util.Scanner;

// The name of this program, or "class", is "time".
public class time
{

public static void main(String[] args)
{

// Use the Scanner class to find out what the user types.
Scanner keyboard = new Scanner(System.in);

// Print a request for the user to enter the input.
System.out.println("How many seconds? Enter an integer followed by space or return.");

/**
* keyboard.nextInt() reads one integer from the keyboard.
* Then it is defined as a variable to hold their input as a total number of seconds.
* I am using long in case the user has a lot of patience to type for a long time, so that they are less likely to break it with large numbers.
*/
long totalSeconds = keyboard.nextInt();

// Dividing any number of seconds by 3600 (60 * 60) will result in hours if using one of the integer types.
// Java will drop the remainder when it is looking for an integer.
long hours = totalSeconds / 3600;

// Remaindering the total number of seconds by 3600 will result in the number of seconds that will be converted into minutes, named remainingSeconds.
long remainingSeconds = totalSeconds % 3600;

// The process repeats, on remainingSeconds. Dividing it, this time by 60, gives us the number of minutes.
long minutes = remainingSeconds / 60;

// Once again we do the remaindering step, this time by 60, to get the number of seconds that will be printed.
long seconds = remainingSeconds % 60;

// Print results by concatenating strings with the output of those operations.
System.out.println("There are " + hours + " hours, " + minutes + " minutes, and " + seconds + " seconds in " + totalSeconds + " seconds.");
}

}

Post a comment in response:

This account has disabled anonymous posting.
If you don't have an account you can create one now.
HTML doesn't work in the subject.
More info about formatting