Adding an incorrect input message to a java input validation program without using if-else statements

Viewed 34

I am making a simple input validation program in Java for a quiz. I have gotten the loop part to work, but I want to improve it so that if one of the inputs is incorrect, it will print something like "one of your inputs is incorrect." before looping again.

I know how to do it with an if statement but I am not allowed to use those for this question for some reason :\

This is what i have so far:

public class Q2 {
    public static void main(String[] args) {
        String username;
        String password;
        Scanner keyboard;
        keyboard = new Scanner(System.in);

        do {

            System.out.print("Please enter your username: ");
            username = keyboard.nextLine();

            System.out.print("Please enter your password: ");
            password = keyboard.nextLine();

        } while(!username.equals("johndoe") || !password.equals("secret1234"));

        System.out.print("You entered the system successfully.");
    }
}

Thanks in advance!

1 Answers

Since you need to do it without an if else statement. I have tested this is working as expected, try it out.

public class Q2 {

    public static void main(String[] args) {
        String username;
        String password;
        Scanner keyboard;
        keyboard = new Scanner(System.in);
        boolean authenticate;

        do {

            System.out.print("Please enter your username: ");
            username = keyboard.nextLine();

            System.out.print("Please enter your password: ");
            password = keyboard.nextLine();


           authenticate= !("johndoe".equals(username)) || !("secret1234".equals(password));


          System.out.println(authenticate?"Please Try again":"");

        } while(authenticate);

        System.out.print("You entered the system successfully.");
    }

}
Related