Saturday, 20 August 2016

Chapter 6 Exercise 25, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

The method returns a string as hours:minutes:seconds. For example, convertMillis(5500) returns a string 0:0:5, convertMillis(100000) returns a string 0:1:40, and convertMillis(555550000) returns a string 154:19:10.

import java.util.Scanner;
 
//**6.25 (Convert milliseconds to hours, minutes, and seconds) Write a method that converts
//milliseconds to hours, minutes, and seconds using the following header:
//public static String convertMillis(long millis)
 
public class ProgrammingExercise6_25 {
 
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
 
  while (true) {
   System.out
     .print("Enter the number of milliseconds (enter 0 to stop):");
   long number = input.nextLong();
   if (number == 0)
    break;
   System.out.println("Converted time is " + convertMillis(number));
  }
 
  System.out.println("Program stops!!");
 }
 
 public static String convertMillis(long millis) {
  long totalMilliseconds = millis;
 
  // Obtain the total seconds since midnight, Jan 1, 1970
  long totalSeconds = totalMilliseconds / 1000;
 
  // Compute the current second in the minute in the hour
  long currentSecond = totalSeconds % 60;
 
  // Obtain the total minutes
  long totalMinutes = totalSeconds / 60;
 
  // Compute the current minute in the hour
  long currentMinute = totalMinutes % 60;
 
  // Obtain the total hours
  long totalHours = totalMinutes / 60;
 
  return totalHours + ":" + currentMinute + ":" + currentSecond;
 
 }
 
}

No comments :

Post a Comment