Home > Software design >  In the code below the loop doesn't end even if I put the correct username
In the code below the loop doesn't end even if I put the correct username

Time:10-04

I was trying to build a simple UI where a user enters a username and if the username is xyz then the user will be shown "enter your password". If the password is xyz1234 then the user will be shown "please wait loading..." and the scanner exits. If the username was incorrect, I tried to code it in a way so that it keeps asking for the username until the correct username is entered.

Apparently, the first part of the code works, if the username is xyz, then the code works correctly and displays what i want it to. However if the username is wrong in the first attempt and right in the second attempt, it still continues to show "incorrect username" instead of showing "enter the password".

The code is shown below:

import java.util.Scanner;
class User_Authentication
{
    public static void main(String args[])
    {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter your Username");
        String username=in.nextLine();
        if(username.equals("xyz"))
        {
            System.out.println("Enter the Password");
            String password=in.nextLine();
            if(password.equals("xyz1234"))
            {
                System.exit(0);
                System.out.println("Welcome");
                System.out.println("Please wait while the system is loading....");
            }
            else
            {
                System.out.println("Your system has been locked for security reasons.");
                System.out.println("Please contact an administrator to reset the password");
                System.out.println("Any attempt to break in the computer will result in self destruction.");
                System.exit(0);
            }
        }
        else
        {
        do
        {
               if(username.equals("xyz"))
               {
                   break;
               }
               System.out.println("Incorrect username");
               System.out.println("Please try again");
               in.nextLine();
        }
        while((username.equals("xyz"))==false);
    }
    }
} ```

CodePudding user response:

Your saying in.nextLine() in your do-while loop, rather than username = in.nextLine()

Replace that and it should work, but overall you're do-while loop needs some work, it's relatively messy. Here's how I would approach it.

do {
    System.out.println("Incorrect username");
    System.out.println("Please try again");
    username = in.nextLine();
} while(username.equals("xyz") == false);
  • Related