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

This program creates a loop that ends when the correct password is input.

My Code

import java.util.Scanner;

public class Password {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        String password = "carrot"; // Use carrot as password when running tests.

        // Write your code here
        while (true) {
            System.out.print("Type the password: ");
            String guess = reader.nextLine();
            if (guess.equals(password)) {
                System.out.println("Right!");
                break;
            }
            System.out.println("Wrong!");
        }
        System.out.println("");
        System.out.println("The secret is: jryy qbar!");
    }
}

Model Code

import java.util.Scanner;

 

public class Password {

 

    public static void main(String[] args) {

        Scanner reader = new Scanner(System.in);

        String password = "carrot"; // Use carrot as password when running tests.

 

        // Write your code here

        while (true) {

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

            String readPassword = reader.nextLine();

 

            if (readPassword.equals(password)) {

                System.out.println("Right!");

                break;

            } else {

                System.out.println("Wrong!");

            }

        }

        

        System.out.println(""); 

        System.out.println("The secret is: jryy qbar!");

    }

}

Comments

The only real difference between the two is that the model code includes the “Wrong!” output as part of the if else statement and I have it as part of the loop. I like mine better but I wonder why they did that?

Leave a comment