如何初始化此变量?

时间:2014-10-07 17:23:56

标签: java jgrasp

我知道我需要初始化变量daysInMonth,但我不知道怎么做,因为它在我需要它的时候确定当天的有效性取决于用户的输入。

int daysInMonth; //number of days in month read in

确定daysInMonth的部分代码

if(month == 1)
   daysInMonth = 31; 

我收到错误的代码

//User number of days in month to check to see if day is valid
if(day > 0 && day <= daysInMonth)
   dayValid = true;
else
   dayValid = false;

5 个答案:

答案 0 :(得分:1)

考虑daysInMonth应该是month的其他值。添加else,或者else if。确保涵盖所有可能的值,包括初始化或异常。

答案 1 :(得分:0)

这种初始化是不够的:

if(month == 1)
   daysInMonth = 31; 

由于只有daysInMonth才会初始化month==1

最安全的方法是在声明时初始化daysInMonth,并在必要时更改其值(基于month)。

int daysInMonth == 31;
if (month == 6)
   daysInMonth = 30;
...

另一种选择是使用一个月的方法并返回daysInMonth。然后,您可以通过调用:

来初始化变量
int daysInMonth = getDaysInMonth(month);

答案 2 :(得分:0)

如何保持简单并按照这样做:

daysInMonth = 31; // Default value for the month
if(month == 2) {
   daysInMonth = 28;  // Change value if the month is febuary
} else if (month == 4 || month == 6 || month== 9 || month==11) {
   daysInMonth = 30; // Change value if the month should have 30 days
}

答案 3 :(得分:0)

您需要保证变量的初始化。

int daysInMonth; //number of days in month read in
if(month == 1)
    daysInMonth = 31; 

这仅在月份为1时初始化变量。如果它不是1,则它仍然未初始化。

有两种方法可以解决这个问题:

1。在开头

初始化变量

通过为您的值提供默认值,您可以保证它不是null

int daysInMonth = 0; //number of days in month read in
if(month == 1)
    daysInMonth = 31; 

2。在每个分支

初始化变量

通过故意不定义它,你可以让编译器告诉你是否缺少任何路径。这对于复杂的if / else语句有用,其中变量具有特定的值,并且你不能例如,对于一个应该为-1的状态,我不小心默认为0。

int daysInMonth; //number of days in month read in
if(month == 1)
    daysInMonth = 31; 
else if(month == 2)
    daysInMonth = 28; 
//...
else if(month == 12)
    daysInMonth = 31; 
else 
    daysInMonth = -1; 

答案 4 :(得分:0)

有很多方法可以解决这个问题,但你可以试试这个:

int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
daysInMonth = days[month-1]]; 

就是这样!您只需要2行代码。

如果你需要检查闰年......你可以试试这个:

int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int[] daysLeapYr = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

if (year % 4 == 0) //Leap year
    daysInMonth = daysLeapYr[month-1]];   //where month is 1-12 (Jan to Dec)
else
    daysInMonth = days[month-1]]; 

这样,您可以使用最少的if-statements保持代码清晰。

如果您没有检查闰年,则甚至不需要任何if-statements

相关问题