首先是TimeClass.java的源代码:
import java.util.*;
import java.text.*;
public class TimeClass {
protected Date date = new Date();
protected SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
protected String dateStr = formatter.format(date);
static void getTime() {
TimeClass timeClass = new TimeClass();
timeClass.date = new Date();
timeClass.dateStr = timeClass.formatter.format(timeClass.date);
System.out.println(timeClass.dateStr);
}
}
class ForTimeClass extends TimeClass {
protected int time1;
static void forGetTime(int time, long atime) {
ForTimeClass forTimeClass = new ForTimeClass();
if (time != 0) {
for (forTimeClass.time1 = 0; forTimeClass.time1 < time; forTimeClass.time1++) {
TimeClass.getTime();
try {
Thread.sleep(atime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} else {
System.out.println("请重新输入大于零的数");
}
}
}
也可以自己根据代码把所用到的对象对应的包全部import一下就好了。
这里为了方便,import部分直接全部import进来。
接下来是GetTime.java源代码,其实就是为了调用TimeClass.java文件的代码。其实可以全部整合到一个文件的,但是为了方便维护,可以不用写成一个Java文件里。
import java.util.Scanner;
public class GetTime {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("请输入运行次数:");
int top = scan.nextInt();
System.out.print("请输入输出间隔(毫秒):");
int top2 = scan.nextInt();
ForTimeClass.forGetTime(top, top2);
}
}
注意:这两个Java文件如果你是初学者,请保证这两个Java文件在同一目录里,且其他Java文件中没有冲突的方法名!
当然如果你是初学者,文件名不用改成其他的。如果要改的话两个文件开头的public class后面的也要改成对应的文件名,且要遵循Java的命名规范。