2016-07-20 8 views
2

変数を週末や休暇(txtファイルに保存されている)に追加するプログラムを作成しようとしています。 私のコードは、それが週末ではないと言っていますが、私は非常に混乱しています。何でもありがとう!Java Calendarが正しい情報を表示しない

コード

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

'String'を比較するために' equals() 'を使用します。 – thegauravmahawar

答えて

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) 
0

あなたは間違った方法でプロパティを使用します。

DAY_OF_WEEKフィールドのgetおよびsetの日:

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を参照してください。 の週の

関連する問題