-1

I'm trying to stop someone from entering a day number which is less than 0 and greater than 31. Its stuck in an infinite loop.

public void setDay(int setDayTo) throws IllegalArgumentException
            {   
                do
                {
                    if(setDayTo <= 0 || setDayTo >31)
                    {
                        System.out.println("Day is not in range from 1 to 31, please" + " " + 
                        "re-enter the date:");
                    }
                    // No Exception thrown
                    day = setDayTo;

                }while(day <= 0 || day > 31);   
            }
SiHa
  • 7,830
  • 13
  • 34
  • 43
Daniel
  • 29
  • 8
  • 1
    You are not throwing any exceptions - how do you expect `setDayTo` to ever change within this loop? – Hulk Nov 06 '16 at 13:50
  • 1
    `day = setDayTo;` is always ran, regardless of the print statement. And you never re-prompt for new input – OneCricketeer Nov 06 '16 at 13:50
  • Any suggestions as to what i should do then? – Daniel Nov 06 '16 at 13:51
  • should i remove the throws statement and the setDayTo statement? – Daniel Nov 06 '16 at 13:51
  • Show a [mcve] for how you are running this method – OneCricketeer Nov 06 '16 at 13:51
  • Basically im taking user input in, i dont want them entering a invalid date. This method is contained in a Date class. The user puts in the date in another class. Ill post some code now – Daniel Nov 06 '16 at 13:53
  • If you have a `throws`, then actually `throw new IllegalArgumentException`... Not just print – OneCricketeer Nov 06 '16 at 13:53
  • System.out.print("Enter the date the account opened: "); int d = keyboardIn.nextInt(); dateOpened.setDay(d); System.out.print("Enter the month the account opened: "); int m = keyboardIn.nextInt(); dateOpened.setMonth(m); System.out.print("Enter the year the account opened: "); int y = keyboardIn.nextInt(); dateOpened.setYear(y); – Daniel Nov 06 '16 at 13:55

1 Answers1

2

Why does statement keep repeating in this error checking code?

Because you never accept new input and update the setDayTo value, and since you're using that unchanging value to set day, if the value is out-of-range to start with, it will be out-of-range forever.

Either have the method throw an exception (probably best, and probably without outputting anything; that would be the job of the code calling it), or have it accept a new value (again, though, that would probably be the job of the code calling it).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875