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
}
}
There are many problems with your code:
IllegalStateException
is not raised by the "not-match", but by the Scanner class, so why catch it?matcher.find()
, I think you want found = matcher.find()
scn.next();
Moreover:
boolean found = false;
with boolean found;
continue;
at the end of a loop is not necessaryFixed code:
boolean found;
do {
System.out.println("ask user for input");
input = scn.next();
found = pattern.matcher(input).find();
if (!found) {
System.out.println("input not valid.");
}
} while (!found);
scn.close();