gpt4 book ai didi

java - 使用 boolean 效用方法评估多个年份以查找闰年

转载 作者:行者123 更新时间:2023-12-01 19:31:43 25 4
gpt4 key购买 nike

大家下午好,我在从 boolean 实用方法计算多个闰年时遇到问题。我被告知要使用循环,但很难弄清楚如何以及在哪里放置它。

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);
}

关于java - 使用 boolean 效用方法评估多个年份以查找闰年,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59254591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com