I want to loop my scanner if the user entered something and it made the statement false in my code, if the user entered a false statement, the loop will continue but if I enter the right statement, it will still continue.
Scanner sc = new Scanner(System.in);
System.out.println("Enter your student number: ");
String sn = sc.nextLine();
String REGEX = "[0-9]{4}.[0-9]{2}.[0-9]{3}";
Pattern pattern = Pattern.compile(REGEX);
Matcher matcher = pattern.matcher(sn);
do {
if (matcher.matches()) {
System.out.println("You have succesfully logged in");
System.out.println("Hello " + sn + " welcome to your dashboard");
}
else
System.out.println("Please enter your student number in this format: 'xxxx-xx-xxx' ");
System.out.println("Enter your student number: ");
sc.nextLine();
} while (true);
>Solution :
I would rewrite it like this
Scanner sc = new Scanner(System.in);
System.out.println("Enter your student number: ");
String sn = sc.nextLine();
String REGEX = "[0-9]{4}.[0-9]{2}.[0-9]{3}";
Pattern pattern = Pattern.compile(REGEX);
while(!pattern.matcher(sn).matches()) {
System.out.println("Please enter your student number in this format: 'xxxx-xx-xxx' ");
System.out.println("Enter your student number: ");
sn = sc.nextLine();
}
System.out.println("You have succesfully logged in");
System.out.println("Hello " + sn + " welcome to your dashboard");