新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

java实现时钟代码如何写,java数字时钟程序

发布时间:2023-08-30 08:01:28

java实现时钟代码如何写

以下是一个简单的Java代码示例,用于实现一个时钟:
```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秒钟,以摹拟时钟每秒的走时效果。
在控制台中运行该程序,可以看到输出的时间会不断更新,摹拟了一个简单的时钟效果。