Home > front end >  Loop if else in scanner
Loop if else in scanner

Time:05-19

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

CodePudding user response:

Matcher matcher = pattern.matcher(sn);

This matches the pattern against what is currently in 'sn'. If 'sn' changes, that does not affect the matcher. If you read another line without assigning the result to anything, that doesn't affect 'sn' or the matcher.

And you have no loop termination - it's just "do while true" with no way out.

So, three problems:

  1. The matcher needs to be created inside the loop.

  2. The result of the second nextLine call needs to be assigned to 'sn'

  3. You need a loop termination. I suggest a flag, 'loggedIn', initially false, set true on successful match, and the loop ends with 'while (!loggedIn)'

CodePudding user response:

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

CodePudding user response:

Take the input scan and pattern matcher inside do while loop

String sn; 
Matcher matcher 
    do {
       sn = sc.nextLine();
       matcher= pattern.matcher(sn);

        if (!matcher.matches()) {
            System.out.println("Please enter your student number in this format: 'xxxx-xx-xxx' ");
            System.out.println("Enter your student number: ");

        }


          
    } while (true);

    System.out.println("You have succesfully logged in");   
    System.out.println("Hello "   sn   " welcome to your dashboard");   

  • Related