import java.util.*;
public class Year
{
public static void main(String [] args)
{
String answer;
int year;
int month;
Scanner input = new Scanner(System.in);
System.out.print("请输入你要判断的年份:");
year = input.nextInt();
if((year%4==0 && year%100!=0) || year%400==0 )
System.out.println(year+"年是闰年");
else
{
System.out.println(year+"年是平年");
}
System.out.print("请输入你要判断的月份:");
month = input.nextInt();
if(month==1 && month==3 && month==5 && month==7
&& month==8 && month==10 && month==12)
{
System.out.println(month+"月有31天");
}
else if (month==4 && month==6 && month==9 && month==11)
{
System.out.println(month+"月有30天");
}
else if (month==2 && ((year%4==0 && year%100!=0) || year%400==0))
{
System.out.println(month+"月有29天");
}
else if (month==2 && !((year%4==0 && year%100!=0) || year%400==0))
{
System.out.println(month+"月有28天");
}
else
{
System.out.println("输入月份错误");
}
System.out.print("是否结束y/n:");
answer = input.next();
if(answer.equals("y"))
{
System.out.println("程序结束");
continue;
}
else
System.out.print("");
}while(!answer.equals("y"));
}
}为啥只有2月份那俩个else if管用,
我输入1月或是4月那俩个就直接打印出了最后一个输入错误了
那个30天的还有31天的else if怎么不起作用?
public class Year
{
public static void main(String [] args)
{
String answer;
int year;
int month;
Scanner input = new Scanner(System.in);
System.out.print("请输入你要判断的年份:");
year = input.nextInt();
if((year%4==0 && year%100!=0) || year%400==0 )
System.out.println(year+"年是闰年");
else
{
System.out.println(year+"年是平年");
}
System.out.print("请输入你要判断的月份:");
month = input.nextInt();
if(month==1 && month==3 && month==5 && month==7
&& month==8 && month==10 && month==12)
{
System.out.println(month+"月有31天");
}
else if (month==4 && month==6 && month==9 && month==11)
{
System.out.println(month+"月有30天");
}
else if (month==2 && ((year%4==0 && year%100!=0) || year%400==0))
{
System.out.println(month+"月有29天");
}
else if (month==2 && !((year%4==0 && year%100!=0) || year%400==0))
{
System.out.println(month+"月有28天");
}
else
{
System.out.println("输入月份错误");
}
System.out.print("是否结束y/n:");
answer = input.next();
if(answer.equals("y"))
{
System.out.println("程序结束");
continue;
}
else
System.out.print("");
}while(!answer.equals("y"));
}
}为啥只有2月份那俩个else if管用,
我输入1月或是4月那俩个就直接打印出了最后一个输入错误了
那个30天的还有31天的else if怎么不起作用?
&& month==8 && month==10 && month==12)你用的是逻辑并"&&",所以你输入1时只满足month==1这个条件,而month==3后面的全不满足,结果这个if返回的值是false,最终当然不执行了。你应该用"||"而不是"&&"
应该用 ||
比如这里:
if(month==1 && month==3 && month==5 && month==7
&& month==8 && month==10 && month==12)
等
返回false,原因与上面分析的一样