为什么 java.util.Date 对象在运行时不更新自身?

问题描述 投票:0回答:1

我需要在程序运行时保存日期,但日期对象在运行时不会自行更新,如何更新日期对象。

public static void main(String[] args) {
    try {
        Scanner input = new Scanner(System.in);
        Date date = new Date();
        BufferedWriter w1 = new BufferedWriter(new FileWriter("C:\\Users\\alifu\\Desktop\\Race\\1.txt"));
        BufferedWriter w2 = new BufferedWriter(new FileWriter("C:\\Users\\alifu\\Desktop\\Race\\2.txt"));
        BufferedWriter w3 = new BufferedWriter(new FileWriter("C:\\Users\\alifu\\Desktop\\Race\\3.txt"));
        BufferedWriter w4 = new BufferedWriter(new FileWriter("C:\\Users\\alifu\\Desktop\\Race\\4.txt"));
        BufferedWriter w5 = new BufferedWriter(new FileWriter("C:\\Users\\alifu\\Desktop\\Race\\5.txt"));
        int n = 0, a = 0, b = 0, c = 0, d = 0, e = 0;
        while (true) {
            System.out.print("Number: ");
            n = input.nextInt();
            if (n < 0) break;
            switch (n) {
            case 1:
                a++;
                w1.write(Integer.toString(a) + " - " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds() + "\n");
                break;
            case 2:
                b++;
                w2.write(Integer.toString(b) + " - " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds() + "\n");
                break;
            case 3:
                c++;
                w3.write(Integer.toString(c) + " - " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds() + "\n");
                break;
            case 4:
                d++;
                w4.write(Integer.toString(d) + " - " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds() + "\n");
                break;
            case 5:
                e++;
                w5.write(Integer.toString(e) + " - " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds() + "\n");
                break;
            default:
                break;
            }
        }
        w1.close();w2.close();w3.close();w4.close();w5.close();
    } catch (IOException e) {
        System.out.println("Error!!");
        e.printStackTrace();
    }
}

在 while 循环中,我选择一个案例,然后在程序运行时写入文本文件,它从用户处获取输入以检测目标文件,但日期对象自程序启动以来给出了相同的信息。

java java-io java.util.date
1个回答
0
投票

正确,因为您只在函数顶部捕获一次日期。 创建对象时捕获日期。 从那时起,它就是一个静态变量。 它不会在后台神奇地更新。

只需将变量创建移至循环中即可:

    while (true) {
        System.out.print("Number: ");
        n = input.nextInt();
        if (n < 0) break;
        Date date = new Date();
© www.soinside.com 2019 - 2024. All rights reserved.