if语句查询问题,eclipse说“死代码”

时间:2011-07-06 15:46:43

标签: java date loops calendar if-statement

首先,非常感谢人们提供的任何帮助!

好的,所以我在这里有这个循环,我似乎遇到了if语句的问题。

Eclipse告诉我下面的查询部分和“else”中的代码是“死代码”:

|| calDateOfDay.DAY_OF_WEEK == Calendar.SUNDAY 

但我不知道为什么。

此外,当它执行时,它总是执行“if”语句中的代码,(据我的理解)这意味着每天都是星期六。但是,我知道这个日子有正确的价值(确实有几天被检查不是星期六)。我知道这一点,因为我已经通过Eclipse中的代码进行了调试,逐个检查日期的值。

老实说,我很困惑,甚至试图解释它! :S

我希望代码能做的是:

  1. 每天取得(一个月的价值,根据月份的不同而不同)并检查一天是星期六还是星期天。
  2. 如果是周六或周日,那么我希望它将当天的“类型”设置为周末,如果不是,我希望它将日期的“类型”设置为工作日。
  3. 基本上就是这样。

            for (DayEntry dayEntry : daySet){
    
                //day value to be filled
                Day day = new Day();
                Calendar calDateOfDay = new GregorianCalendar();
                //set the date of the day
                calDateOfDay.setTime(dayEntry.getDateOfDay());
                day.setDate(calDateOfDay);
    
                //set the hours of the day
                day.setWorkHours(dayEntry.getHours());
    
                if (Calendar.DAY_OF_WEEK == Calendar.SATURDAY || Calendar.DAY_OF_WEEK == Calendar.SUNDAY ){
    
                    day.setType(DayType.WEEK_END);
    
                }else{
    
                    day.setType(DayType.WEEK_DAY);
    
                }
    
    
                //add the day to the week
                week.addDay(day);   
    
            }
    

    现在,我上面编写代码的原因是因为当我编写如下代码时,Eclipse告诉我应该以静态方式访问静态变量DAY_OF_WEEK,所以我'我也不确定这是否会导致问题。

            for (DayEntry dayEntry : daySet){
    
                //day value to be filled
                Day day = new Day();
                Calendar calDateOfDay = new GregorianCalendar();
                //set the date of the day
                calDateOfDay.setTime(dayEntry.getDateOfDay());
                day.setDate(calDateOfDay);
    
                //set the hours of the day
                day.setWorkHours(dayEntry.getHours());
    
                if (calDateOfDay.DAY_OF_WEEK == Calendar.SATURDAY || calDateOfDay.DAY_OF_WEEK == Calendar.SUNDAY ){
    
                    day.setType(DayType.WEEK_END);
    
                }else{
    
                    day.setType(DayType.WEEK_DAY);
    
                }
    
    
                //add the day to the week
                week.addDay(day);   
    
            }
    

4 个答案:

答案 0 :(得分:7)

DAY_OF_WEEK是一个常量,包含星期几的字段编号。您的代码使用它,就好像它包含该字段的一样,但它没有。

要修复代码,只需将calDateOfDay.DAY_OF_WEEK替换为calDateOfDay.get(Calendar.DAY_OF_WEEK)

答案 1 :(得分:1)

Calendar.DAY_OF_WEEK是一个静态变量,它存储一个整数,该整数引用Calendar实例中的一个字段,该字段包含星期几。

您要做的是calDateOfDay.get(Calendar.DAY_OF_WEEK)

答案 2 :(得分:0)

|| calDateOfDay.DAY_OF_WEEK == Calendar.SUNDAY 

这意味着编译器会将boolean语句的第一部分评估为始终为真。

答案 3 :(得分:0)

常量Calendar.SATURDAYCalendar.DAY_OF_WEEK仅为static final int,其值为7.因此calDateOfDay.DAY_OF_WEEK == Calendar.SATURDAY始终为true

您需要使用Calendar.get(int field)

检查相应的字段
calDateOfDay.get(Calendar.DAY_OF_WEEK)== Calendar.SATURDAY