Object-Oriented Programming with Java, part I – Exercise 20

This program accepts a username and password and then outputs a response if they are accepted or not.

My Code

import java.util.Scanner;

public class Usernames {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);

        System.out.print("Type your username: ");   // Input username
        String userName = reader.nextLine();

        System.out.print("Type your password: ");
        String passWord = reader.nextLine();

        if (userName.equals("alex") && passWord.equals("mightyducks")) {
            System.out.println("You are now logged into the system!");
        } else if (userName.equals("emily") && passWord.equals("cat")) {
            System.out.println("You are now logged into the system!");
        } else {
            System.out.println("Your username or password was invalid!");
        }
    }
}

Model Code

import java.util.Scanner;

 

public class Usernames {

 

    public static void main(String[] args) {

        Scanner reader = new Scanner(System.in);

 

        System.out.print("Type your username: ");

        String username = reader.nextLine();

        System.out.print("Type your password: ");

        String password = reader.nextLine();

 

        // NOTE: This solution would be quite ugly should there be more users.

        // In the following weeks we'll see how to do this better.

        if ((username.equals("alex") && password.equals("mightyducks")) || 

            (username.equals("emily") && password.equals("cat"))) {

            System.out.println("You are now logged into the system!");

        } else {

            System.out.println("Your username or password was invalid!");

        }

    }

}

Comments

My solution is fairly close to theirs except they have placed all the usernames and passwords on one line whereas I have separated them into if else statements. That does save some repetition though.

Leave a Reply

Your email address will not be published. Required fields are marked *