Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I continue to prompt for input, if my REGEX is not matched?

I’m trying to get this loop to continue. So far, when input is not matched to my REGEX, "input not valid" gets displayed but loop won’t continue. What am I missing here?

Apreciate your help!

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {

public static void main(String[] args) {

    String input;
    //some variables
    Pattern pattern = Pattern.compile(REGEX);
    Scanner scn = new Scanner(System.in);


    boolean found = false;
    do {
        System.out.println("ask user for input");
        input = scn.next();
        Matcher matcher = pattern.matcher(input);
        try {
            matcher.find();
            //some Code
            found = true;
            scn.close();
        
        } catch (IllegalStateException e) {
            System.out.println("input not valid."); //stuck here
            scn.next();
            continue;
        }
    } while (!found);

            // some more Code

}
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It seems to me like scn.next() after your "input not valid" line isn’t doing anything, but it’s going to wait for the user to input a string. That’s why it looks like the loop isn’t continuing: it’s waiting for you to input a string because of that line. However, when you do input something, that input will just be thrown away. Removing that line seems like it will do the trick.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading