首页 > 解决方案 > 如何正确组合我的循环(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();
      }
     }
    }
  }
 }

标签: java

解决方案


只是修复你的代码,而不是想出解决这个问题的最佳方法,因为网上有一百万个例子可以做到这一点。

问题出在这部分:-

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

请缩进您的代码并使用大括号。


推荐阅读