第六章第二十五题(将毫秒数转换成小时数、分钟数和秒数)(Convert milliseconds to hours, minutes, and seconds)
-
**6.25(将毫秒数转换成小时数、分钟数和秒数)使用下面的方法头,编写一个将毫秒数转换成小时数、分钟数和秒数的方法。
public static String convertMillis(long millis)
该方法返回形如“小时:分钟:秒”的字符串。例如:convertMillis(5500)返回字符串0:0:5,convertMillis(100000)返回字符串0:1:40,convertMillis(555550000)返回字符串154:19:10。编写一个测试程序,提示用户输入一个long型的毫秒数,以“小时:分钟:秒”的格式显示一个字符串。
**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)
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. Write a test program that prompts the user to enter a long integer for milliseconds and displays a string in the format of hours:minutes:seconds. - 参考代码:
package chapter06;
import java.util.Scanner;
public class Code_25 {
public static void main(String[] args) {
Scanner inputScanner = new Scanner(System.in);
System.out.print("enter a long integer for milliseconds: ");
long millis = inputScanner.nextLong();
System.out.printf("The time is %s", convertMillis(millis));
}
public static String convertMillis(long millis) {
String timeString = "";
long totalSeconds = millis / 1000;
long currentSecond = totalSeconds % 60;
long totalMinutes = totalSeconds / 60;
long currentMinute = totalMinutes % 60;
long totalHours = totalMinutes / 60;
timeString = String.valueOf(totalHours) + ":" + String.valueOf(currentMinute) + ":" + String.valueOf(currentSecond);
return timeString;
}
}
- 结果显示:
enter a long integer for milliseconds: 555550000
The time is 154:19:10
Process finished with exit code 0
版权声明:本文为jxh1025_原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。