简体   繁体   中英

Program overloaded, how can I fix it?

Ok, so this is my assignment - I simply have to return true if date # 1 is later than date # 2, but I don't think I wrote the isLater method incorrectly because when I run the program, it says java.lang.StackOverflowError. Here's my code:

import java.util.Scanner;

public class Dates
{
  /**
   *  returns true if month1/day1/year1 is later than
   *  month2/day2/year2; otherwise returns false
   */
  public static boolean isLater(int month1, int day1, int year1,
                                int month2, int day2, int year2)
  {

    if (isLater (month1, day1, year1, month2, day2, year2))
        return true;
    else
        return false;

  }

  public static void main(String[] args)
  {
    Scanner kb = new Scanner(System.in);

    System.out.print("Enter the first date  (month day year): ");
    int month1 = kb.nextInt();
    int day1 = kb.nextInt();
    int year1 = kb.nextInt();

    System.out.print("Enter the second date (month day year): ");
    int month2 = kb.nextInt();
    int day2 = kb.nextInt();
    int year2 = kb.nextInt();

    System.out.println();  // blank line

    String msg = month1 + "/" + day1 + "/" + year1;
    if (isLater(month1, day1, year1, month2, day2, year2))
      msg += " IS ";
    else
      msg += " is NOT ";
    msg += "later than " + month2 + "/" + day2 + "/" + year2;
    System.out.println(msg);
    kb.close();
  }
}

What should I do to fix that? In other words, how else can I use the isLater method to compare the two dates?

Thanks! Simone

The isLater method is calling itself . So it goes into infinite loop and causes the error

A good way to check would be to parse the user entered date into a Date object using SimpleDateFormat You can use Date.getTime to then compare the two Date objects

Edit The reason it's recursive is because of flawed logic If your if else statement runs the "if" clause, you're running the method again with the same args. So it will go to the if clause again and go round forever

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