2016-07-20 20 views
2

Ich versuche ein Programm zu erstellen, das zu einer Variablen hinzugefügt wird, wenn es kein Wochenende oder Feiertag ist (gespeichert in einer TXT-Datei). Mein Code sagt, dass es ein Wochenende ist, obwohl es nicht ist, und ich bin sehr verwirrt. Alles wird helfen, danke!Java-Kalender zeigt keine richtigen Informationen an

-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 ++; 
    } 
    } 
} 
+0

Verwenden Sie 'equals()', um 'String's zu vergleichen. – thegauravmahawar

Antwort

3

Das ist falsch:

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

cal.DAY_OF_WEEKnicht der Woche den aktuellen Tag ist, dass der Kalender eingestellt ist, ist eine Konstante, die mit dem get Verfahren verwendet werden soll, erhalten der aktuelle Wochentag:

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

Sie verwenden, um die Eigenschaften in einer falschen Weise:

if (cal.get(Calendar.Day_OF_WEEK) == Calendar.SATURDAY || cal.get(Calendar.Day_OF_WEEK) == Calendar.SUNDAY){ 
       System.out.println("Weekend"); 
       System.exit(0); 
      } 

Siehe Java doc:

DAY_OF_WEEK Feldnummer für get und stellen Sie den Tag angibt, der Woche.