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

This exercise uses a class to create a random password out of a string of characters, in this case the alphabet.

My Code

Program

public class Program {
    public static void main(String[] args) {
        PasswordRandomizer randomizer = new PasswordRandomizer(13);
        System.out.println("Password: " + randomizer.createPassword());
        System.out.println("Password: " + randomizer.createPassword());
        System.out.println("Password: " + randomizer.createPassword());
        System.out.println("Password: " + randomizer.createPassword());
    }
}

PasswordRandomizer

import java.util.Random;

public class PasswordRandomizer {

    // Define the variables
    private int length;
    private Random random = new Random();

    public PasswordRandomizer(int length) {
        // Initialize the variable
        this.length = length;
        this.random = new Random();
        
    }

    public String createPassword() {
        // write code that returns a randomized password
        int i = 0;
        String password = "";
        while (i < this.length){
            
            int number = random.nextInt(26);
            char symbol = "abcdefghijklmnopqrstuvwxyz".charAt(number);
            password = password + symbol;
            
            i++;
        }
        
        return password;
    }
}

Model Code

Program

public class Program {

    public static void main(String[] args) {

        PasswordRandomizer randomizer = new PasswordRandomizer(13);

        System.out.println("Password: " + randomizer.createPassword());

        System.out.println("Password: " + randomizer.createPassword());

        System.out.println("Password: " + randomizer.createPassword());

        System.out.println("Password: " + randomizer.createPassword());

    }

}

PasswordRandomizer

import java.util.Random;

 

public class PasswordRandomizer {

    // Define the variables

    private Random random = new Random();

    private int length;

 

    public PasswordRandomizer(int length) {

        // Initialize the variable

        this.length = length;

    }

 

    public String createPassword() {

        // write code that returns a randomized password

        String characters = "abcdefghijklmnopqrstuvwxyz";

 

        String password = "";

        int numberOfCharacters = this.length;

        

        while (numberOfCharacters > 0) {

            int luku = this.random.nextInt(characters.length());

            char c = characters.charAt(luku);

            password = password + c;

            numberOfCharacters--;

        }

        

        return password;

    }

}

Comments

That took way to long, including arrays and a couple of restarts. In the end it was fairly simple but not as nice as the model code.

Leave a comment