温馨提示×

java实现时钟代码怎么写

小亿
117
2023-08-29 16:29:04
栏目: 编程语言
Java开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

以下是一个简单的Java代码示例,用于实现一个时钟:

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class Clock {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
while (true) {
LocalTime currentTime = LocalTime.now();
String formattedTime = currentTime.format(formatter);
System.out.println(formattedTime);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

这段代码使用了java.time包中的LocalTime类来获取当前时间,并使用DateTimeFormatter类将时间格式化为"HH:mm:ss"的字符串。然后,通过一个无限循环来不断获取当前时间并打印出来。使用Thread.sleep()方法使程序休眠1秒钟,以模拟时钟每秒的走时效果。

在控制台中运行该程序,可以看到输出的时间会不断更新,模拟了一个简单的时钟效果。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:java怎么实现时间时钟

0