First off, sorry the code is kinda messy. It didn’t format very well. My assignment is to randomly generate a password consisting of uppercase and lowercase letters, with the length being specified by the user. So far, my code is unfinished but that’s because I’ve run into a problem.
My password will display lowercase and uppercase letters, but it won’t be long enough.
For example, if the person wants a password with a length of 14, I’ll only get a password that’s less than that. It’s never the length that it’s supposed to be.
import java.util.Scanner;
import java.util.Random;
public class Password{
public static void main(String [] args){
Scanner in = new Scanner(System.in);
int passwordLength = 0;
Random randNum = new Random();
int randNumAscii = 0;
String generatedPassword = "";
System.out.print("Password Length (1-14): ");
passwordLength = in.nextInt();
for(int count = 0; count < passwordLength; count++){
randNumAscii = randNum.nextInt(123);
if(randNumAscii >= 65 && randNumAscii <= 90 || randNumAscii >= 97 && randNumAscii <= 122)
generatedPassword += (char)randNumAscii;
else
randNumAscii = randNum.nextInt(123);
}
System.out.println(generatedPassword);
}
}
It’s because you only add a character to the generated password if it’s in your selected range. If a character is randomized outside of
randNumAscii >= 65 && randNumAscii <= 90 || randNumAscii >= 97 && randNumAscii <= 122you never append it to the string.What you can do is either have a while loop inside the for loop that continues until that condition is met, or continue the for loop but decrease the count variable with one so a new character is generated “with that index” so to speak.