Password Program

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

Answer:

secret

No... actually that is not such a great password. A password cracker would guess it in about two seconds

Password Program

Sounds like you need to consult Nigerian Security Services, Ltd. Here is their program for generating random passwords:

import java.util.*;

class PasswordGenerator
{
  public static void main ( String[] args )
  {
    Scanner scan = new Scanner( System.in );
    Random rand = new Random();    
    int digits = 0;
    
    while ( digits < 5 )
    {
      System.out.println("Your password must have at least 5 characters.");
      System.out.print("How many characters do you want in your password? ");
      digits = scan.nextInt();
    }

    String choices = "abcdefghijklmnopqrstuvwxyz" ;
    choices = choices + choices.toUpperCase() ;
    choices = choices + "1234567890" ;

    String password = "";
    int j = 0;
    while ( j<digits )
    {
      password = password + choices.charAt( rand.nextInt( choices.length() ) );
      j = j + 1;
    }
    
    System.out.println("Here is your password: " + password );
  }
}

Here are a few runs of the program:

K:/>java PasswordGenerator
Your password must have at least 5 characters.
How many characters do you want in your password? 4
Your password must have at least 5 characters.
How many characters do you want in your password? 3
Your password must have at least 5 characters.
How many characters do you want in your password? 8
Here is your password: BaXpmUsA

K:/>java PasswordGenerator
Your password must have at leas 5 characters.
How many characters do you want in your password? 12
Here is your password: ly3YFAhM8HDH

The details of this program are explained in the next few pages.

QUESTION 14:

What is the purpose of the following loop from the program:

    while ( digits < 5 )
    {
      System.out.println("Your password must have at least 5 characters.");
      System.out.print("How many characters do you want in your password? ");
      digits = scan.nextInt();
    }