使用布尔实用程序方法评估多年以查找闰年
Evaluate Multiple Years to Find a Leap Year Using a Boolean Utility Method
大家下午好,
我在使用布尔实用程序方法计算多个闰年时遇到问题。我被告知要使用循环,但很难弄清楚如何以及在哪里放置它。
import java.util.Scanner;
public class LeapYear {
private static boolean isLeapYear(int year) {
if (year % 400 == 0 && year % 100 == 0) {
return true;
}
if (year % 100 == 0) {
return false;
}
if (year % 4 == 0) {
return true;
}
else {
return false;
}
}
public static void main(String[] args) {
int quitter = 0;
int negative = 0;
int year = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a year or -1 to quit: ");
year = scan.nextInt();
while (year != -1 && year < 1582) {
System.out.print("The Gregorian calendar was not adopted until 1582, please enter a year after 1582: ");
year = scan.nextInt();
}
if(year == -1) {
negative += year;
quitter++;
}
System.out.println(isLeapYear(year));
}
}
只需使用 do-while 循环:
public static void main(String[] args) {
int year = 0;
Scanner scan = new Scanner(System.in);
do{
System.out.println("Enter a year or -1 to quit: ");
year = scan.nextInt();
while (year < 1582) {
System.out.print("The Gregorian calendar was not adopted until 1582, please enter a year after 1582: ");
year = scan.nextInt();
}
if(year != -1) {
System.out.println(isLeapYear(year));
}
}while(year!=-1);
}
大家下午好, 我在使用布尔实用程序方法计算多个闰年时遇到问题。我被告知要使用循环,但很难弄清楚如何以及在哪里放置它。
import java.util.Scanner;
public class LeapYear {
private static boolean isLeapYear(int year) {
if (year % 400 == 0 && year % 100 == 0) {
return true;
}
if (year % 100 == 0) {
return false;
}
if (year % 4 == 0) {
return true;
}
else {
return false;
}
}
public static void main(String[] args) {
int quitter = 0;
int negative = 0;
int year = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a year or -1 to quit: ");
year = scan.nextInt();
while (year != -1 && year < 1582) {
System.out.print("The Gregorian calendar was not adopted until 1582, please enter a year after 1582: ");
year = scan.nextInt();
}
if(year == -1) {
negative += year;
quitter++;
}
System.out.println(isLeapYear(year));
}
}
只需使用 do-while 循环:
public static void main(String[] args) {
int year = 0;
Scanner scan = new Scanner(System.in);
do{
System.out.println("Enter a year or -1 to quit: ");
year = scan.nextInt();
while (year < 1582) {
System.out.print("The Gregorian calendar was not adopted until 1582, please enter a year after 1582: ");
year = scan.nextInt();
}
if(year != -1) {
System.out.println(isLeapYear(year));
}
}while(year!=-1);
}