是否有以下代码的类似形式:
if(month == 4,6,9,11)
{
do something;
}
Run Code Online (Sandbox Code Playgroud)
或者必须是:
if(month == 4 || month == 6 etc...)
{
do something;
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试撰写一份if
声明,检查本月是否超过31天.
编辑
我想真正的问题是我不知道我学到了什么,但每次我尝试使用sun网站关于java时它都会让我感到困惑.我的问题是,如果我从一个用户和一天获得一个月的时间,并将其放入MM/dd格式并进行评估,那么是否有更简单的方法来检查月份和日期是否有效以及在我检查之后有效我可以用我所拥有的格式打印MM/dd.如果无效打印一行显示无效的月份或日期.
irr*_*ble 27
if( 0x0A50 & (1<<month) != 0 )
Run Code Online (Sandbox Code Playgroud)
伙计,这太荒谬了.(month==4||month==6||month==9||month==11)
完全没问题.
sch*_*der 12
如果您使用的是C或Java,则可以执行以下操作:
switch (month) {
case 4:
case 6:
case 9:
case 11:
do something;
break;
}
Run Code Online (Sandbox Code Playgroud)
在某些语言中,你甚至可以写作case 4,6,9,11:
.其他可能性是创建一个数组[4,6,9,11],一些函数式语言应该允许类似的东西if month in [4,6,9,11] do something;
正如Lior所说,这取决于语言.
编辑:顺便说一句,你也可以这样做(只是为了好玩,坏代码,因为不可读):
if ((abs(month-5) == 1) || (abs(month-10) == 1)) do_something;
Run Code Online (Sandbox Code Playgroud)
你没有指定语言,但如果你使用的是Java,那么你可以采用第二种方式,或者使用switch:
switch(month) {
case 4:
case 6:
case 9:
case 11:
do something;
}
Run Code Online (Sandbox Code Playgroud)
或者,您可能会发现有用且更干净(取决于设计)不对代码进行硬编码,而是将它们保留在其他位置:
private static final Collection<Integer> MONTHS_TO_RUN_REPORT = Arrays.asList(4, 6, 9, 11);
....
if (MONTHS_TO_RUN_REPORT.contains(month)) {
do something;
}
Run Code Online (Sandbox Code Playgroud)
这个月
System.out.println("This month has " + new GregorianCalendar().getActualMaximum(Calendar.DAY_OF_MONTH) + " days in it.");
Run Code Online (Sandbox Code Playgroud)
if语句检查本月是否有31天
if (31 == new GregorianCalendar().getActualMaximum(Calendar.DAY_OF_MONTH))
{
System.out.println("31 days on this month");
}
else
{
System.out.println("Not 31 days in this month");
}
Run Code Online (Sandbox Code Playgroud)
写出所有月份的天数
Calendar cal = new GregorianCalendar();
for (int i = 0; i < 12; i++)
{
cal.set(2009, i, 1); //note that the month in Calendar goes from 0-11
int humanMonthNumber = i + 1;
int max = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println("The " + humanMonthNumber + ". month has " + max + " days.");
}
Run Code Online (Sandbox Code Playgroud)
输出:
This month has 30 days in it.
Not 31 days in this month
The 1. month has 31 days.
The 2. month has 28 days.
The 3. month has 31 days.
The 4. month has 30 days.
The 5. month has 31 days.
The 6. month has 30 days.
The 7. month has 31 days.
The 8. month has 31 days.
The 9. month has 30 days.
The 10. month has 31 days.
The 11. month has 30 days.
The 12. month has 31 days.
Run Code Online (Sandbox Code Playgroud)
Java的一个相当字面的翻译将是:
if (Arrays.binarySearch(new int[] { 4, 6, 9, 11 }, month) >= 0) {
Run Code Online (Sandbox Code Playgroud)
我不知道4,6,9和11有什么特别之处.你可能最好使用enum,EnumSet
或者枚举方法.OTOH,也许JodaTime做了一些有用的事情.