我开始自学Java,并且一直在做在线练习。
我无法获得正确的打印:每当我想通过输入 -1 退出程序时,它都会打印 -1 而不是最后输入的年份。如何解决此问题,以便打印最后输入的年份而不是 -1 ?我已经尝试了很多东西,例如 arrayLists 和其他循环,但我似乎没有让它工作。
谢谢。
import java.util.*;
public class Miniprojekti4_3 {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int command = 0;
int year = 0;
int days = 365;
try {
System.out.println("The program will ask you to input years. You can quit by typing -1 ");
while (true) {
System.out.print("Insert year: ");
year = Integer.parseInt(input.nextLine());
if (year == -1) {
break;
}
}
} catch (Exception e) {
System.out.println("Error: program closing..");
System.exit(1);
}
if (year % 4 == 0 && year % 400 == 0) {
System.out.println("In the year " + year + " there is " + (days+1) +" days. ");
} else {
// if the year is not a leap year
System.out.println("In the year " + year + " there is " + days +" days. ");
}
}
}
最佳答案
如果您移动整个 if/else 部分来检查闰年并在 while(true) block 内显示日期,您应该得到您正在寻找的内容:
while (true)
{
System.out.print("Insert year: ");
year = Integer.parseInt(input.nextLine());
if (year == -1)
{
break;
}
if (year % 4 == 0 && year % 400 == 0) // if the year is a leap year.
{
System.out.println("In the year " + year + " there is " + (days+1) +" days. ");
}
else // if the year is not a leap year
{
System.out.println("In the year " + year + " there is " + days +" days. ");
}
}
关于Java:虽然(true)没有得到正确的打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38209387/