【发布时间】:2020-03-17 19:56:14
【问题描述】:
这是作业问题:
"编写一个程序,以日期为输入,输出日期的季节。输入是一个字符串表示月份,一个int表示日期。
例如:如果输入是:
4 月 11 日 输出是:
春天 另外,检查 string 和 int 是否有效(实际的月份和日期)。
例如:如果输入是:
蓝色 65 输出是:
无效 "
我的代码如下:
'''
String inputMonth;
int inputDay;
inputMonth = scnr.next();
inputDay = scnr.nextInt();
if( ((inputMonth == "March") || (inputMonth == "march")) && ((inputDay >= 20) && (inputDay <= 31))){
System.out.println("Spring");
}
else if( ((inputMonth == "April") || (inputMonth == "april")) && ((inputDay >= 1) && (inputDay <= 30))){
System.out.println("Spring");
}
else if( ((inputMonth == "May") || (inputMonth == "may")) && ((inputDay >= 1) && (inputDay <= 31))){
System.out.println("Spring");
}
else if( ((inputMonth == "June") || (inputMonth == "june")) && ((inputDay >= 1) && (inputDay <= 20))){
System.out.println("Spring");
}
else if( ((inputMonth == "June") || (inputMonth == "june")) && ((inputDay >= 21) && (inputDay <= 30))){
System.out.println("Summer");
}
else if( ((inputMonth == "July") || (inputMonth == "july")) && ((inputDay >= 1) && (inputDay <= 31))){
System.out.println("Summer");
}
else if( ((inputMonth == "August") || (inputMonth == "august")) && ((inputDay >= 1) && (inputDay <= 31))){
System.out.println("Summer");
}
else if( ((inputMonth == "September") || (inputMonth == "september")) && ((inputDay >= 1) && (inputDay <= 21))){
System.out.println("Summer");
}
else if( ((inputMonth == "September") || (inputMonth == "september")) && ((inputDay >= 22) && (inputDay <= 30))){
System.out.println("Autumn");
}
else if( ((inputMonth == "October") || (inputMonth == "october")) && ((inputDay >= 1) && (inputDay <= 31))){
System.out.println("Autumn");
}
else if( ((inputMonth == "November") || (inputMonth == "november")) && ((inputDay >= 22) && (inputDay <= 30))){
System.out.println("Autumn");
}
else if( ((inputMonth == "December") || (inputMonth == "december")) && ((inputDay >= 1) && (inputDay <= 20))){
System.out.println("Autumn");
}
else if( ((inputMonth == "December") || (inputMonth == "december")) && ((inputDay >= 21) && (inputDay <= 31))){
System.out.println("Winter");
}
else if( ((inputMonth == "January") || (inputMonth == "january")) && ((inputDay >= 1) && (inputDay <= 31))){
System.out.println("Winter");
}
else if( ((inputMonth == "February") || (inputMonth == "february")) && ((inputDay >= 1) && (inputDay <= 29))){
System.out.println("Winter");
}
else if( ((inputMonth == "March") || (inputMonth == "march")) && ((inputDay >= 1) && (inputDay <= 19))){
System.out.println("Winter");
}
else{
System.out.println("Invalid");
}
'''
我认为问题在于它不能正确读取字符串和整数,但我不确定为什么。
我也知道可能有更短的方法可以做到这一点,但我还不知道如何,如果有人也愿意帮助我,我将不胜感激。
提前谢谢你
【问题讨论】:
-
另外,我认为你误解了你的任务。该示例在一行中显示月份和日期,但您的程序似乎希望单独输入这些值。在这种情况下,您应该发布第二个问题,因为答案将与这个问题大不相同。
-
查看 String 类的 Java API 并寻找不同类型的
equals方法。这将使您的任务更轻松。 -
原发帖者只是求助,我不知道为什么这些问题无法回答以帮助教育人们。该操作使用对象身份的等效性,即存储在内存中的哈希值。要修复代码,您需要比较字符串值。而不是 inputMonth == "april" 它应该是 inputMonth.equals("april") 我还建议在输入上做 toLowerCase
标签: java string integer user-input