newbie_224466
newbie_224466

Reputation: 37

While loop for re-prompt user after invalid input continues in java

I want to re-prompt the user after a invalid input (empty or does not exist). The code below helps me do that but even if a valid input is given, it will still prompt the user for another input. How can I stop the loop from running again once a valid input is inserted?

    //get user input
    String year = JOptionPane.showInputDialog("Enter input");

    try{
        while (true) {
            List <WebElement> PageScrubberPagelet = dr.findElements(By.xpath("//li[@class='_3d5d']//a[contains(@data-key,'')]"));            
            for (WebElement el:PageScrubberPagelet) {
                if (!(el.getAttribute("data-key")).contains(year) || year.equals("")) {
                    year = JOptionPane.showInputDialog(null, "Invalid input. Please re-enter (recent/ YYYY)", 
                        "Information", JOptionPane.INFORMATION_MESSAGE);

                } else {
                    //find and click on the input year
                    WebElement yearButton = dr.findElement(By.xpath("//a[contains(@data-key,'" + year + "')]"));                        
                    yearButton.click(); 
                    break;
                }
            }
        }
    } catch(Exception e){
        Logger.getLogger(ExpandFacebook.class.getName()).log(Level.SEVERE, "Invalid input!", e);
    } 

If the while loop is replace with if, it will only allow once for a invalid input and will not re-prompt the user for a third time.

Upvotes: 0

Views: 1678

Answers (2)

m_callens
m_callens

Reputation: 6360

Use this template as a guide for you to solve the problem! Shouldn't be too hard, just a simple do-while loop. Since you want what's inside to execute at least once to get the first set of input to test, then loop from there on if necessary:

do
{
    <GET USER INPUT>
} while (<USER INPUT> != <CORRECT DATA>);

Upvotes: 1

Gabe Sechan
Gabe Sechan

Reputation: 93726

The break only breaks the inner most loop (the for loop). You need to then break out from the outermost loop. A better way to do this is

    boolean goodInput = false;
    do {
        for (WebElement el:PageScrubberPagelet) {
            if (!(el.getAttribute("data-key")).contains(year) || year.equals("")) {
                year = JOptionPane.showInputDialog(null, "Invalid input. Please re-enter (recent/ YYYY)", 
                    "Information", JOptionPane.INFORMATION_MESSAGE);

            } else {
                //find and click on the input year
                WebElement yearButton = dr.findElement(By.xpath("//a[contains(@data-key,'" + year + "')]"));                        
                yearButton.click(); 
                goodInput = true;
                break;
            }
        }
    } while (!goodInput);

Upvotes: 0

Related Questions