如果不是周末或假日(存储在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 ++;
}
}
}
答案 0 :(得分:3)
这是错误的:
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)
答案 1 :(得分:0)
您以错误的方式使用属性:
if (cal.get(Calendar.Day_OF_WEEK) == Calendar.SATURDAY || cal.get(Calendar.Day_OF_WEEK) == Calendar.SUNDAY){
System.out.println("Weekend");
System.exit(0);
}
请参阅Java doc:
DAY_OF_WEEK获取和设置的字段编号,表示日期 周。