      1  /**

      2     This program generates a random password.

      3  */

      4  public class PasswordGenerator

      5  {

      6     public static void main(String[] args)

      7     {

      8        String result = makePassword(8);

      9        System.out.println(result);

     10     }

     11

     12     /**

     13        Generates a random password.

     14        @param length the length of the password

     15        @return a password of the given length with one digit and one

     16        special symbol

     17     */

     18     public static String makePassword(int length)

     19     {

     20        String password = "";

     21

     22        // Pick random letters

     23

     24        for (int i = 0; i < length - 2; i++)

     25        {

     26           password = password + randomCharacter("abcdefghijklmnopqrstuvwxyz");

     27        }

     28

     29        // Insert two random digits

     30

     31        String randomDigit = randomCharacter("0123456789");

     32        password = insertAtRandom(password, randomDigit);

     33        String randomSymbol = randomCharacter("+-*/?!@#$%&");

     34        password = insertAtRandom(password, randomSymbol);

     35        return password;

     36     }

     37

     38     /**

     39        Returns a string containing one character randomly chosen from a given string.

     40        @param characters the string from which to randomly choose a character

     41        @return a substring of length 1, taken at a random index

     42     */

     43     public static String randomCharacter(String characters)

     44     {

     45        int n = characters.length();

     46        int r = (int)(n * Math.random());

     47        return characters.substring(r, r + 1);

     48     }

     49

     50     /**

     51        Inserts one string into another at a random position.

     52        @param str the string into which another string is inserted

     53        @param toInsert the string to be inserted

     54        @return the result of inserting toInsert into str

     55     */

     56     public static String insertAtRandom(String str, String toInsert)

     57     {

     58        int n = str.length();

     59        int r = (int) ((n + 1) * Math.random());

     60        return str.substring(0, r) + toInsert + str.substring(r);

     61     }

     62  }