我已经编写了程序并运行了它,但是我不知道如何在我使用无效数字运行程序时防止两个 println 语句都出现。它基本上是一个程序,您可以在其中输入月份和日期(以数值表示),输出将是季节。这是代码:
public class Solstice {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int month;
int day;
String season = "seasons";
System.out.println("Enter a month: ");
month = in.nextInt();
System.out.println("Enter a day: ");
day = in.nextInt();
String winter = "winter";
String spring = "spring";
String summer = "summer";
String fall = "fall";
System.out.println("Month="+ month +" Day= "+day);
if (month <= 3)
{
season = winter;
}
else if (month <= 6)
{
season = spring;
}
else if (month <= 9)
{
season = summer;
}
else if (month <= 12)
{
season = fall;
} else {
System.out.println("The value is invalid.");
}
System.out.println(season);
}
}
最佳答案
写:
String season = null;
然后在最后一个if之前检查:
if(season == null){
//print invalid
} else {
//print corresponding season
}
关于java - 我有一个 if 语句问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35074068/