if-else-else if [英] if-else-else if
问题描述
我是java的初学者,我正在做一些练习题来提高我的java技能。
I am a beginner in java and i am doing some practiceit questions to brush up on my java skills.
编写一个名为season的方法,它将两个整数作为参数表示一个月和一天,并返回一个字符串,表示该月和日的季节。假设月份被指定为1到12之间的整数(1月1,2月2,依此类推),月份的日期是1到31之间的数字。
Write a method named season that takes two integers as parameters representing a month and day and that returns a String indicating the season for that month and day. Assume that months are specified as an integer between 1 and 12 (1 for January, 2 for February, and so on) and that the day of the month is a number between 1 and 31.
如果日期介于12/16和3/15之间,则应返回Winter。如果日期在3/16到6/15之间,则应返回Spring。如果日期在6月16日到9月15日之间,则应返回夏季。如果日期在9月16日到12月15日之间,则应返回秋季。
If the date falls between 12/16 and 3/15, you should return "Winter". If the date falls between 3/16 and 6/15, you should return "Spring". If the date falls between 6/16 and 9/15, you should return "Summer". And if the date falls between 9/16 and 12/15, you should return "Fall".
public static String season(int month,int day){
if(month>=9 && month<=12 && day==15||day==16){
return "Fall";
}
else if (month>=4 && month<=6 && day==16||day==15){
return "Spring";
}
else if (month>=6 && month<=9 && day==16||day==15){
return "Summer";
}
else {
return"Winter";
}
}
但我没有得到输出。但它似乎对我来说。任何人都可以告诉我哪里出错了?
But i'm not getting the output.But it seems right to me.Anyone can tell me where did i go wrong?
推荐答案
||
的优先级低于&&
并且您的条件看起来不正确 - 您可能想要写下这样的内容:
||
has lower precendence than &&
and your conditions don't look correct - you probably wanted to write something like:
if((month == 9 && day >= 16) //September, on or after the 16th
|| month == 10 //or October
|| month == 11 //or November
|| (month == 12 && day <=15)) { //or December, but before or on the 15th
return "Fall";
}
(其他条件的评论相同)
(same comment for the other conditions)
你可以通过使用一点点破解来缩短它,但可读性可能不那么好(值得商榷):
You could make it shorter by using a little hack, but readability is maybe not as good (debatable):
int mdd = month * 100 + day; //date in MDD format, for example 507 for May 7th
if (mdd >= 916 && mdd <= 1215) {
return "Fall";
}
这篇关于if-else-else if的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!