Reputation:
I'm trying to make a program that adds to a variable if its not a weekend or a holiday (stored in a txt file). My code is saying it is a weekend even though it is not and I am very confused. Anything will help thanks!
Code
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 ++;
}
}
}
Upvotes: 2
Views: 56
Reputation: 206796
This is wrong:
if (cal.DAY_OF_WEEK == Calendar.SATURDAY || cal.DAY_OF_WEEK == Calendar.SUNDAY)
cal.DAY_OF_WEEK
is not the current day of the week that the calendar is set to, it is a constant that is to be used with the get
method to get the current day of the week:
if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
Upvotes: 3
Reputation: 69440
You use the properties in a wrong way:
if (cal.get(Calendar.Day_OF_WEEK) == Calendar.SATURDAY || cal.get(Calendar.Day_OF_WEEK) == Calendar.SUNDAY){
System.out.println("Weekend");
System.exit(0);
}
See the Java doc:
DAY_OF_WEEK Field number for get and set indicating the day of the week.
Upvotes: 0