简体   繁体   中英

How do I combine my loops properly(Java)?

I am trying to write a code for my High School class where I enter a year and have the program determine if it's a leap year. I have most of the code down, but I'm having trouble with getting it right. We aren't supposed to be able to enter a year before 1582 unless it's the flag that we're using (I'm using -1 as my flag). Whenever I input a year under 1582 after inputting a valid year (say inputting 2000 and then 1581) the program just ends, and I don't know how to get that to change. My code is listed below:

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

Just fixing your code, not trying to come up with the best way to solve this as there are a million examples online for doing this.

The problem is with this part:-

while (year != -1) {
    if (year >= 1582) {
       ...
    }
}

If year entered is less than 1582, it goes into an infinite while loop because you don't have a way to get the input again. It keeps checking the last input. To fix this, change it to:-

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

And please indent your code and use braces.

I think no one should be taught to make such complex if and while codes... The less you use them, the better. Always try to eliminate complexity, if there's anything too hard to understand in your code try to find a way to make it simpler. One way of doing this is to make code under if statements as brief as possible, and never, ever use nested ifs.

Of course that's my point of view. Here's a simpler example that does pretty much the same as the logic you posted, just for comparison.

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    while (true) {
        System.out.println("Enter a year after 1582 (Type -1 to stop): ");
        int year = scan.nextInt();
        if (year == -1) break;
        if (year <= 1582) {
            System.out.println("ERROR! YEAR MUST BE AFTER 1582!");
            continue;
        }
        if (year % 4 == 0
                && (year % 100 != 0
                || year % 100 == 0
                && year % 400 == 0)) System.out.println(year + " is a leap year.");
        else System.out.println(year + " is not a leap year.");
    }
}

Hope it helps!

Years less than 1581 is handled only in the first while loop.

If you enter a year >= 1582 control goes off to the second while loop. When you provide the next input, there is no code handling the condition where year < 1582, and it runs into an infinite loop.

Advice:

  1. make sure the code is formatted properly in the question.
  2. Redesign the code. may be like

     public class foo{ public boolean checkLeapYear(int year){ //logic to check for leapyear } public static void main(String[] args){ int year = 0 //initialize; boolean result = false; //create foo class while(year != -1){ //Print message to enter year year = //readinput... if(year < 1582){ //print message to enter year >=1582 }else{ result = foo.checkLeapYear(year); if(result){ //Print leap }else{ //Print not leap } } } } } 

All the best..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM