Java 日历未显示正确的信息

标签 java

我正在尝试制作一个程序,如果不是周末或假期(存储在 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/

相关文章:

java - 向 session 添加属性的测试方法失败

java - 我使用 Hystrix(1.5.18) ,并设置参数 ErrorThresholdPercentage=30,始终在标记成功时切换断路状态

java - 为什么泛型到对象的类型转换是隐式的?

java - 内存映射文件从由换行符分隔的大文件中读取

java - Itext 从现有的 pdf 中获取字段坐标

java - 我在 spout 类中的失败方法仅适用于第一个 bolt ,从第二个 bolt 开始它不起作用。

java - 如何使用 Selenium 和 Java 在自动化测试中单击按钮

java - 在 Java 中获取 JCombobox 中项目的正确位置

java - SPAnish) 体系结构,在哪里放置公共(public)代码?

java.lang.ClassFormatError