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
}
}
>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.