Java切换没有看到表达式的值

时间:2014-11-06 02:06:36

标签: java switch-statement

我创建了一个方法来根据月份计算一年中的天数

public int howManyDays()
{
    int totalDays = 0;

    System.out.println(dDay);

    switch(dDay)
    {
    case 1:
        totalDays = 0;
    case 2:
        totalDays = 31;
    case 3:
        totalDays = totalDays + 28;
    case 4:
        totalDays = totalDays + 31;
    case 5:
        totalDays = totalDays + 30;
    case 6: 
        totalDays = totalDays + 31;
    case 7:
        totalDays = totalDays + 30;
    case 8:
        totalDays = totalDays + 31;
    case 9:
        totalDays = totalDays + 31;
    case 10:
        totalDays = totalDays + 30;
    case 11:
        totalDays = totalDays + 31;
    case 12:
        totalDays = totalDays + 30;
    }

    totalDays = totalDays + dDay;

    return totalDays;

}

由于某种原因,当我用驱动程序调用它时,它只返回dDay的数量,交换机没有被输入。我知道dDay具有我给它的任何价值,因为方法开头的print语句证实了它。此外,如果我在开关之前给dDay一个IN方法的值,它将进入开关并按预期工作。我不明白为什么println可以看到dDay的值,但是开关不能。

这是我用来为数据成员赋值的方法。

public void setDate(int month, int day, int year)
    {
        int monthLength = 0;
        int leapYear = 0;

        dYear = year;

        if (month > 0 && month < 13)
            dMonth = month;

        if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
            monthLength = 31;
        else if (month == 4 || month == 6 || month == 9 || month == 11)
            monthLength = 30;
        else if (month == 2)
            monthLength = 28;

        if(year % 400 == 0 || year % 100 != 0 && year % 4 == 0)
            leapYear = 1;

        if (monthLength == 31 && day < 32 && day > 0)
            dDay = day;
        else if (monthLength == 30 && day < 31 && day > 0)
            dDay = day;
        else if (monthLength == 28 && day < (29 + leapYear) && day > 0)
            dDay = day;                 
    }

这是我的司机

import java.util.*;

    public class Driver
    {
        static Scanner console = new Scanner(System.in);
        public static void main (String[] args)
        {
            Date zeroDate = new Date ();

            zeroDate.setDate(6,11,2016);
            System.out.println(zeroDate);
            System.out.println(zeroDate.howManyDays());

        }
    }

和构造函数

public class Date
{
    private int dMonth;
    private int dDay;
    private int dYear;

    public Date()
    {
        dMonth = 1;
        dDay = 1;
        dYear = 1900;
    }

    public Date (int month, int day, int year)
    {
        dMonth = month;
        dDay = day;
        dYear = year;
    }

0 个答案:

没有答案