#Help with input validation loop breaking

8 messages · Page 1 of 1 (latest)

hidden ledge
#

Im trying to validate if a user's input is a valid integer and 0 or higher. But the loop just exits itself.

upper scaffoldBOT
#

This post has been reserved for your question.

Hey @hidden ledge! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

hidden ledge
#
int staffYearsOfServiceInt = 0;
                do {
                    String staffYearsOfService = JOptionPane.showInputDialog(null, "Enter the staff's years of service", "College Accounting Program", JOptionPane.QUESTION_MESSAGE);
                    try {
                        //Pass staffYearsOfService into an int variable called staffYearsOfServiceInt
                        staffYearsOfServiceInt = Integer.parseInt(staffYearsOfService);
                        if (staffYearsOfServiceInt < 0) {
                            JOptionPane.showMessageDialog(null, "Invalid years of service. Please enter a number greater than 0", "College Accounting Program", JOptionPane.ERROR_MESSAGE);
                        }
                        // If the user enters a non-integer, catch the error and display an error message
                    } catch (NumberFormatException e) {
                        JOptionPane.showMessageDialog(null, "Invalid years of service. Please enter a number greater than 0", "College Accounting Program", JOptionPane.ERROR_MESSAGE);
                    }
                    // Loop until the user enters a valid year
                } while (staffYearsOfServiceInt < 0);
#

if you enter a non valid input the error dialog pops up but when you click "OK" on it, the loop doesn't work like it's suppose to

#

if I change while(staffYearsOfServiceInt <0) to while (staffYearsOfServiceInt <1) it works. But I need to also beable to enter 0 as an answer

lusty quiver
#

You set it equals to zero right at the beginning

hidden ledge