java - 如何正确组合我的循环(Java)?
问题描述
我正在尝试为我进入一年的高中课程编写代码,并让程序确定它是否是闰年。我有大部分代码,但我无法正确处理。我们不应该能够输入 1582 年之前的一年,除非它是我们正在使用的标志(我使用 -1 作为我的标志)。每当我在输入有效年份(比如输入 2000 和 1581)后输入低于 1582 的年份时,程序就结束了,我不知道如何改变它。我的代码如下:
import java.util.Scanner;
public class Lab3_3 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int year;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a year after 1582(Type -1 to stop): ");
year = scan.nextInt();
while (year < 1582 && year != -1) {
System.out.println("ERROR! YEAR MUST BE AFTER 1582!");
System.out.println("Enter a new year(Type -1 to stop): ");
year = scan.nextInt();
}
if (year == -1)
System.out.println("You're done!");
else
while (year != -1) {
if (year >= 1582) {
boolean leap = false;
if (year % 4 == 0) {
if (year % 100 == 0) {
if (year % 400 == 0)
leap = true;
else
leap = false;
} else
leap = true;
} else
leap = false;
if (leap) {
System.out.println(year + " is a leap year.");
System.out.println("Enter a new year(Type -1 to stop): ");
year = scan.nextInt();
} else {
System.out.println(year + " is not a leap year.");
System.out.println("Enter a new year(Type -1 to stop): ");
year = scan.nextInt();
}
}
}
}
}
解决方案
只是修复你的代码,而不是想出解决这个问题的最佳方法,因为网上有一百万个例子可以做到这一点。
问题出在这部分:-
while (year != -1) {
if (year >= 1582) {
...
}
}
如果输入的年份小于 1582,它将进入无限循环,因为您无法再次获取输入。它不断检查最后一个输入。要解决此问题,请将其更改为:-
while (year != -1) {
if (year >= 1582) {
...
} else {
System.out.println("ERROR! YEAR MUST BE AFTER 1582!");
System.out.println("Enter a new year(Type -1 to stop): ");
year = scan.nextInt();
}
}
请缩进您的代码并使用大括号。
推荐阅读
- javascript - 未通过 Redux 处理的 Promise
- c# - C# 完成后重复一个 mp3 文件
- php - 使用phpmailer发送表单时没有页面刷新
- c - ESP32 如何重置与 PCNT 一起使用的 GPIO 引脚,以便它们也可用于 EXT1 从深度睡眠中唤醒?
- codenameone - Codename One 应用程序的线程计数
- python-3.x - 两个看起来应该做同样事情但输出不同结果的python循环?
- php - 为 Angular 应用程序配置 php 后端和 mysql 数据库
- java - Spring MockMVC redirectUrlPattern 抛出“No Ant-style path pattern”
- dart - Dart 2.0 中是否有任何密封类替代方案?
- react-native - Google 地方信息 API:INVALID_REQUEST