gpt4 book ai didi

Java 日历不显示正确的信息

转载 作者:行者123 更新时间:2023-11-30 08:00:31 25 4
gpt4 key购买 nike

我正在尝试制作一个程序,如果不是周末或假期(存储在 txt 文件中),它会添加到变量中。我的代码说这是一个周末,尽管它不是,我很困惑。任何事情都会有所帮助,谢谢!

代码

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;

public class Main {

public static void main(String[] args) {

int day = 0;
while (true) {

// Gets current date
Calendar cal = Calendar.getInstance();
cal.add(cal.DATE, day);
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
String formatted = format.format(cal.getTime());

System.out.println("\nDate: " + formatted);

try {
// If its Saturday or Sunday
if (cal.DAY_OF_WEEK == Calendar.SATURDAY || cal.DAY_OF_WEEK == Calendar.SUNDAY) {
System.out.println("Weekend");
System.exit(0);
}
else {
// Opens the dates.txt
BufferedReader reader = new BufferedReader(new FileReader("dates.txt"));
String line = reader.readLine(); // The current line

// Loops through the file until end
while (line != null) {
if (line == formatted)// If holiday is current day {
System.out.println("Holiday");
System.exit(0);
}
line = reader.readLine(); // Goes to the next line
}
System.out.println("School");
day += 1;
}
}
catch(FileNotFoundException e){}
catch(IOException e){}

try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e1) {
System.out.println("ERROR: Sleep Failed");
}
day ++;
}
}
}

最佳答案

这是错误的:

if (cal.DAY_OF_WEEK == Calendar.SATURDAY || cal.DAY_OF_WEEK == Calendar.SUNDAY)

cal.DAY_OF_WEEK 不是日历设置的当前星期几,它是一个常量,将与 get 获取当前星期几的方法:

if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)

关于Java 日历不显示正确的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38474683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com