温馨提示×

java实现时钟代码怎么写

小亿
105
2023-08-29 16:29:04
栏目: 编程语言

以下是一个简单的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秒钟,以模拟时钟每秒的走时效果。

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

0