Ben Collins
Ben Collins

Reputation: 67

If the input is incorrect and I require to put the input in again, how do I do that?

If the input is incorrect and I require to put the input in again, how do I do that?

public static void main(String[] args) throws InterruptedException
    {
        String welcomeMessage = "Welcome to our system! Please enter your details to log in.\n";
        System.out.println(welcomeMessage);

        TimeUnit.SECONDS.sleep(3);

        Scanner inputUserName = new Scanner(System.in);

        String userName = "User Name: ";
        System.out.println(userName);

        String userNameInput = inputUserName.nextLine();

        while (true)
        {

            if (userNameInput.contains("@"))
            {
                System.out.println("Shap");
                break;
            } else
            {
                System.out.println("\nPlease enter a valid user name!");
                String enterAgain = userName;
                System.out.println(enterAgain);
            }
        }
    }

Upvotes: 0

Views: 58

Answers (2)

prachi
prachi

Reputation: 305

You can do this by using while loop -

 Scanner inputUserName = new Scanner(System.in);
    String userName = "User Name: ";
        System.out.println(userName);

        String userNameInput = inputUserName.nextLine();

        while (!userNameInput.contains("@"))
        {
                System.out.println("\nPlease enter a valid user name!");
                System.out.println(userName);
                userNameInput = inputUserName.nextLine()
            }
        }
    System.out.println("Shap");

Upvotes: 0

vijay
vijay

Reputation: 75

Try using this in while Condition

Scanner inputUserName = new Scanner(System.in); 

String userNameInput = inputUserName.nextLine();


while (!userNameInput.contains("@")) 

{

    System.out.println("\nPlease enter a valid user name!");

    userNameInput = inputUserName.nextLine(); 
}

System.out.println("Success");

Upvotes: 1

Related Questions