-1

我知道我需要初始化变量 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;
4

5 回答 5

1

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

于 2014-10-07T17:28:32.477 回答
0

这个初始化是不够的:

if(month == 1)
   daysInMonth = 31; 

因为daysInMonth只会在month==1.

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

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

另一种选择是有一个方法需要一个月并返回daysInMonth. 然后你可以通过调用来初始化你的变量:

int daysInMonth = getDaysInMonth(month);
于 2014-10-07T17:25:40.890 回答
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
}
于 2014-10-07T17:29:02.880 回答
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 语句可能很有帮助,例如,您不希望意外地默认为 0 来表示应该为 -1 的状态。

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; 
于 2014-10-07T17:31:03.693 回答
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.

于 2014-10-07T17:33:07.637 回答