I had to write a program that generated a random password given choices about characters and length (you can see the options in the menu that's in the code below).
The program will work perfectly if you choose option #4 (because it includes all the possible characters). The others tend to get stuck in an infinite loop somewhere. Where is the error in my code logic.
Any help would be greatly appreciated. Thanks
CODE
import java.util.Scanner;
import java.util.Random;
class Password
{
public static void main(String [] args)
{
Scanner in = new Scanner (System.in);
Random randNumList = new Random ();
System.out.println(" Password Generation Menu ");
System.out.println("****************************************************************");
System.out.println("*\n[1] Lowercase Letters *");
System.out.println("*\n[2] Lowercase & Uppercase Letters *");
System.out.println("*\n[3] Lowercase, Uppercase, & Numbers *");
System.out.println("*\n[4] Lowercase, Uppercase, Numbers, and Punctuation *");
System.out.println("*\n[5] Quit *");
System.out.println("****************************************************************");
System.out.print("Enter Selection (1-5): ");
String selection = in.next();
System.out.println("");
System.out.print("Password Length (1-14): ");
int passLength = in.nextInt();
for (int i = 1; i <= passLength; i++)
{
int charNum = (int)(randNumList.nextDouble()*(126-48) + 48);
Boolean condState;
if(selection.equals("1"))
{
condState = (charNum <= 122 && charNum >= 97);
}
else if(selection.equals("2"))
{
condState = ((charNum <=122 && charNum >= 97) || (charNum <= 90 && charNum >= 65));
}
else if(selection.equals("3"))
{
condState = ((charNum <=122 && charNum >= 97) || (charNum <= 90 && charNum >= 65) || (charNum <= 57 && charNum >= 48));
}
else if(selection.equals("4"))
{
condState = (charNum <= 126 && charNum >= 48);
}
else
{
condState = charNum == 0;
System.out.println("Program Terminated");
System.exit(0);
}
while(!condState)
{
charNum = (int)(randNumList.nextDouble()*(126-48) + 48);
}
System.out.print((char)(charNum));
}
}
}