用Java创建类TimerAlarm,让它继承Thread并实现一个秒表的功能,不要使用内置的Timer类,程序运行的结果应该如下图所示:先按照时:分:秒打印时间,然后换一行打印总的秒数。使用输入输出流,将文件words.txt 文件内容读出,然后以倒序的方式重新保存在信的文件newwords.txt里面,并为每个单词编号。如果在保存的时候newwords文件已经存在,应该产生FileFundException,并将其捕获处理。
时间: 2023-06-19 17:10:51 浏览: 129
以下是 TimerAlarm 类的实现:
```java
import java.io.*;
import java.util.Scanner;
public class TimerAlarm extends Thread {
private int hour;
private int minute;
private int second;
private boolean isRunning;
private long startTime;
private long elapsedTime;
public TimerAlarm() {
this.hour = 0;
this.minute = 0;
this.second = 0;
this.isRunning = false;
this.startTime = 0;
this.elapsedTime = 0;
}
public void run() {
try {
while (true) {
Thread.sleep(1000);
if (isRunning) {
elapsedTime = System.currentTimeMillis() - startTime;
second = (int) (elapsedTime / 1000) % 60;
minute = (int) ((elapsedTime / (1000*60)) % 60);
hour = (int) ((elapsedTime / (1000*60*60)) % 24);
System.out.print(String.format("%02d:%02d:%02d", hour, minute, second) + "\r");
System.out.flush();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void startTimer() {
isRunning = true;
startTime = System.currentTimeMillis();
}
public void stopTimer() {
isRunning = false;
elapsedTime = System.currentTimeMillis() - startTime;
}
public long getElapsedTime() {
return elapsedTime;
}
public static void main(String[] args) {
TimerAlarm timer = new TimerAlarm();
timer.start();
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
while (!input.equalsIgnoreCase("stop")) {
input = scanner.nextLine();
if (input.equalsIgnoreCase("start")) {
timer.startTimer();
} else if (input.equalsIgnoreCase("stop")) {
timer.stopTimer();
System.out.println();
System.out.println("Elapsed time: " + timer.getElapsedTime() / 1000 + " seconds");
}
}
scanner.close();
try {
BufferedReader reader = new BufferedReader(new FileReader("words.txt"));
BufferedWriter writer = new BufferedWriter(new FileWriter("newwords.txt"));
String line;
int count = 0;
while ((line = reader.readLine()) != null) {
count++;
}
reader.close();
String[] words = new String[count];
reader = new BufferedReader(new FileReader("words.txt"));
for (int i = 0; i < count; i++) {
words[i] = reader.readLine();
}
reader.close();
writer = new BufferedWriter(new FileWriter("newwords.txt"));
for (int i = count - 1; i >= 0; i--) {
writer.write((count - i) + ". " + words[i]);
writer.newLine();
}
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在 `main` 方法中,我们创建了一个 `TimerAlarm` 对象,并启动了它的线程。然后使用 `Scanner` 对象从标准输入中读取用户输入的命令,如果输入为 `start`,则调用 `startTimer` 方法启动计时器;如果输入为 `stop`,则调用 `stopTimer` 方法停止计时器,并输出经过的时间。最后,我们使用输入输出流从 `words.txt` 文件中读取数据,并以倒序的方式重新保存到 `newwords.txt` 文件中,并为每个单词编号。
需要注意的是,在保存数据到 `newwords.txt` 文件时,如果该文件已经存在,会抛出 `FileFundException` 异常。我们需要在 `try-catch` 块中捕获该异常,并进行处理。
阅读全文