这可能很简单,但我现在无法解决这个问题。我只是想一起打印几个整数,以便输出
2004年是闰年
2013年不是闰年
public class Ex1partA {
public static void main(String[] args) {
int year = 2004;
if(year%400==0){
System.out.println("2004 is a leap year");
}else if(year%100==0){
System.out.println("2004 is not a leap year");
}else if(year%4==0){
System.out.println("2004 is a leap year");
}else{
System.out.println("2004 is not a leap year");
}
}
{
int year1 = 2013;
if(year1%400==0){
System.out.println("2013 is a leap year");
}else if(year1%100==0){
System.out.println(" 2013 is not a leap year");
}else if(year1%4==0){
System.out.println("2013 is a leap year");
}else{
System.out.println("2013 is not a leap year");
}
}
}
答案 0 :(得分:3)
你在想它。只需使用这样的简单if-else
。
int year = 2004;
if (year % 4 == 0) {
System.out.println("2004 is a leap year");
} else {
System.out.println("2004 is not a leap year");
}
int year1 = 2013;
if (year1 % 4 == 0) {
System.out.println("2013 is a leap year");
} else {
System.out.println("2013 is not a leap year");
}
你甚至可以将它移动到一个方法,你可以通过年份,它会为你显示结果。像这样的东西
public static void main(String[] args) {
int year = 2004;
checkLeapYear(year);
int year1 = 2013;
checkLeapYear(year1);
}
private static void checkLeapYear(int year) {
if (year % 4 == 0) {
System.out.println(year + " is a leap year");
} else {
System.out.println(year + " is not a leap year");
}
}
答案 1 :(得分:1)
您应该将非静态块代码放入main或将其作为static-block进行打印2013年不是闰年。
公共课Ex1partA {
public static void main(String[] args) {
int year = 2004;
if (year % 400 == 0) {
System.out.println("2004 is a leap year");
} else if (year % 100 == 0) {
System.out.println("2004 is not a leap year");
} else if (year % 4 == 0) {
System.out.println("2004 is a leap year");
} else {
System.out.println("2004 is not a leap year");
}
// Method#1
{
int year1 = 2013;
if (year1 % 400 == 0) {
System.out.println("2013 is a leap year");
} else if (year1 % 100 == 0) {
System.out.println(" 2013 is not a leap year");
} else if (year1 % 4 == 0) {
System.out.println("2013 is a leap year");
} else {
System.out.println("2013 is not a leap year");
}
}
}
// Method#2
static {
int year1 = 2013;
if (year1 % 400 == 0) {
System.out.println("2013 is a leap year");
} else if (year1 % 100 == 0) {
System.out.println(" 2013 is not a leap year");
} else if (year1 % 4 == 0) {
System.out.println("2013 is a leap year");
} else {
System.out.println("2013 is not a leap year");
}
}
}
答案 2 :(得分:1)
你的问题有点模糊,但看起来你有两个独立的块。因为你的main方法被括在一组大括号中,然后下一个“语句”被包含在一组单独的大括号中。编辑大括号,以便main方法包含两个块。