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

Loop if else in scanner

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 :

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

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");
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