Leaper 如果表达错误
Leaper if expression is faulty
import java.util.*;
public class LeapYear {
public static void main (String args[]) {
Scanner scan = new Scanner(System.in);
int userInput = scan.nextInt();
boolean leapYearisTrue = false;
while ( userInput != 0 ) {
if (userInput % 4 == 0) {
if ( (userInput % 100 == 0) && (userInput % 400 != 0) ) {
leapYearisTrue = false;
System.out.println (leapYearisTrue);
}
else {
leapYearisTrue = true;
System.out.println (leapYearisTrue);
}
userInput = scan.nextInt();
}
}
}
}
每当我输入一个闰年的值时,程序都会顺利运行并执行预期的操作:
2000
true
1960
true
400
true
但是每当我输入一个非闰年时,它不会打印错误,也不会再打印一个数字是闰年:
403
400
2000 ( this is a leap year , yet it doesn't print true)
2004
您需要在 if (userInput % 4 == 0)
条件中添加一个 else
条件。
试试这个:
import java.util.*;
public class LeapYear {
public static void main(String args[]) {
System.out.println("Enter the year: \n");
Scanner scan = new Scanner(System.in);
int userInput = scan.nextInt();
boolean leapYearisTrue = false;
while (userInput != 0) {
if (userInput % 4 == 0) {
if (userInput % 100 == 0) {
if (userInput % 400 != 0) {
leapYearisTrue = true;
System.out.println(leapYearisTrue);
}
} else {
leapYearisTrue = true;
System.out.println(leapYearisTrue);
}
userInput = scan.nextInt();
}
}
}
}
import java.util.*;
public class LeapYear {
public static void main (String args[]) {
Scanner scan = new Scanner(System.in);
int userInput = scan.nextInt();
boolean leapYearisTrue = false;
while ( userInput != 0 ) {
if (userInput % 4 == 0) {
if ( (userInput % 100 == 0) && (userInput % 400 != 0) ) {
leapYearisTrue = false;
System.out.println (leapYearisTrue);
}
else {
leapYearisTrue = true;
System.out.println (leapYearisTrue);
}
userInput = scan.nextInt();
}
}
}
}
每当我输入一个闰年的值时,程序都会顺利运行并执行预期的操作:
2000
true
1960
true
400
true
但是每当我输入一个非闰年时,它不会打印错误,也不会再打印一个数字是闰年:
403
400
2000 ( this is a leap year , yet it doesn't print true)
2004
您需要在 if (userInput % 4 == 0)
条件中添加一个 else
条件。
试试这个:
import java.util.*;
public class LeapYear {
public static void main(String args[]) {
System.out.println("Enter the year: \n");
Scanner scan = new Scanner(System.in);
int userInput = scan.nextInt();
boolean leapYearisTrue = false;
while (userInput != 0) {
if (userInput % 4 == 0) {
if (userInput % 100 == 0) {
if (userInput % 400 != 0) {
leapYearisTrue = true;
System.out.println(leapYearisTrue);
}
} else {
leapYearisTrue = true;
System.out.println(leapYearisTrue);
}
userInput = scan.nextInt();
}
}
}
}