我在尝试在Eclipse中添加else语句时遇到了问题。我相信我这样做是正确的,因为我正在检查我可能犯的任何错误。我也在课堂上遵循了教授的指示,但我们在尝试添加else语句时遇到了同样的问题。我记得它第一次工作很奇怪。 我得到的错误是“令牌上的语法错误”,否则“,”是预期的。 我想要做的是额外的信用分配,我们创建一个程序,用户输入月份,然后程序告诉当月有多少天。这是我目前的代码。 对不起,它是在一张图片中,我只是让我的朋友借用我的USB驱动器,认为Eclipse会自动在桌面上创建一个工作区,以防我断开闪存驱动器并编写代码....
https://s27.postimg.org/7h8c11eyb/myjavacode.png
import java.util.Scanner;
public class HowManyDaysInYourMonth {
public static void main(String[] args) {
System.out.println("Please enter the month:");
Scanner myScanner=new Scanner(System.in);
String month;
month=myScanner.next();
if(month=="January"||month=="january"||month=="March"||month=="march"||month=="May"||month=="may"||month=="July"||month=="july"||month=="August"||month=="august"||month=="October"||month=="october"||month=="December"||month=="december");{
System.out.println(month+" has 31 days.");}
else if (month=="February"||month=="february");{
System.out.println(month+" has 29 days, but on leap years, February has 28 days.");
}else if (month=="April"||month=="april"||month=="June"||month=="june"||month=="September"||month=="september"||month=="November"||month=="november");{
System.out.println(month+" has only 30 days.");
}
myScanner.close();
}
}
答案 0 :(得分:0)
这应该有效:
import java.util.Scanner;
public final class Main {
public static final void main(final String[] args) {
System.out.println("Please enter the month:");
final Scanner scanner = new Scanner(System.in);
String month = scanner.next();
if (month == "January" || month == "january" || month == "March" || month == "march" || month == "May"
|| month == "may" || month == "July" || month == "july" || month == "August" || month == "august"
|| month == "October" || month == "october" || month == "December" || month == "december") {
System.out.println(month + " has 31 days.");
} else if (month == "February" || month == "february") {
System.out.println(month + " has 29 days, but on leap years, February has 28 days.");
} else if (month == "April" || month == "april" || month == "June" || month == "june" || month == "September"
|| month == "september" || month == "November" || month == "november") {
System.out.println(month + " has only 30 days.");
}
scanner.close();
}
}
在Java中,if-else语句如下所示:
if(condition) {
[...]
} else {
[...]
}
此外,变量名称如" myScanner"不应该被使用,因为"我的"在这种情况下,并没有描述相关信息,但使代码的可读性降低。