out.println(sdf.format(new Date()));
时间: 2023-11-17 18:32:30 浏览: 28
这是 Java 代码语句,主要是使用 SimpleDateFormat 类将当前日期格式化为指定格式的字符串,并使用 System.out.println() 方法将其输出到控制台。其中,sdf 格式化对象是通过 new SimpleDateFormat() 方法创建的,"new Date()" 表示获取当前时间。
相关问题
优化这段代码,使其运行结果只显示一行import java.text.SimpleDateFormat; import java.util.Date; class Timer implements Runnable { public void run() { while(true) { SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println(sdf.format(new Date())); try { Thread.sleep(1000); } catch(InterruptedException e) {e.printStackTrace(); } } } } class Watch { public static void main(String[] args) { Thread thread=new Thread(new Timer()); thread.start(); } }
可以将实例化SimpleDateFormat对象和输出语句移到while循环外,避免每次循环都创建对象,同时使用System.out.print()代替System.out.println(),使输出不换行。代码如下:
```
import java.text.SimpleDateFormat;
import java.util.Date;
class Timer implements Runnable {
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public void run() {
while (true) {
System.out.print(sdf.format(new Date()) + " ");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Watch {
public static void main(String[] args) {
Thread thread = new Thread(new Timer());
thread.start();
}
}
```
优化这段代码import java.text.SimpleDateFormat; import java.Date.*; class Time implements Runnable throws InterruptedExpection { void run(); { while(ture) { SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println(sdf.sdf(new Date())); Tread.sleep(1000); } } } class Watch { public static void main(String[] args) { Thead tread=new Thead(new Timer()); tread.start(); } }
有几个错误需要修正:
1. `java.util.Date` 应该是 `import java.util.Date;` 而不是 `import java.Date.*;`
2. `void run();` 应该是 `public void run() { ... }`,缺少 `public` 和方法体的大括号。
3. `while(ture)` 应该是 `while(true)`,单词拼写错误。
4. `Tread.sleep(1000);` 应该是 `Thread.sleep(1000);`,单词拼写错误,`Thread` 是正确的类名。
修改后的代码如下:
```
import java.text.SimpleDateFormat;
import java.util.Date;
class Timer implements Runnable {
public void run() {
while (true) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(new Date()));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Watch {
public static void main(String[] args) {
Thread thread = new Thread(new Timer());
thread.start();
}
}
```
这个代码实现了一个计时器,每秒钟输出当前时间。其中 `Timer` 类实现了 `Runnable` 接口,用于在新线程中运行计时器逻辑;`Watch` 类则在主线程中创建并启动了一个新线程来运行计时器。修改后的代码可以正常运行,输出如下:
```
2021-06-22 13:03:31
2021-06-22 13:03:32
2021-06-22 13:03:33
2021-06-22 13:03:34
2021-06-22 13:03:35
...
```