帮我用java写一个实时时钟
时间: 2024-05-12 14:19:02 浏览: 4
下面是一个简单的Java代码示例,用于创建实时时钟:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class RealTimeClock {
public static void main(String[] args) {
while (true) {
SimpleDateFormat dateFormat = new SimpleDateFormat("kk:mm:ss");
Date currentTime = new Date();
String formattedTime = dateFormat.format(currentTime);
System.out.println(formattedTime);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
这个程序使用了一个无限循环来不断更新时间。在循环中,我们创建了一个SimpleDateFormat对象,用于将时间格式化为"kk:mm:ss"的格式。然后,我们获取当前时间,使用SimpleDateFormat对象将其格式化,并将结果存储在formattedTime变量中。最后,我们打印formattedTime变量的值,并使用Thread.sleep()方法暂停1秒钟,以便在下一次循环中更新时间。