Reputation: 129
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);
}
}
Upvotes: 0
Views: 373
Reputation: 67502
As you said, your issue lies here:
randNumAscii = randNum.nextInt(123);
if(randNumAscii >= 65 && randNumAscii <= 90 || randNumAscii >= 97 && randNumAscii <= 122)
generatedPassword += (char)randNumAscii;
else
randNumAscii = randNum.nextInt(123);
Let me explain why:
Basically, when userSelection == 2
, your code says: "Once for each space in the given length, pick some random character. If it's uppercase or lowercase, add it. Otherwise, change it." But, what you forget to do, is append the "changed" random character.
What you need to do here is something like this (pseudocode):
randNumAscii = [random from 0 to 123]
while randNumAscii is not uppercase and not lowercase:
randNumAscii = [random from 0 to 123]
append (char)randNumAscii to generatedPassword
Since this is an assignment, I leave the implementation to you. Because I'm not sure of your skill level, you may want to read the documentation on while
.
Upvotes: 1
Reputation: 17973
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 <= 122
you 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.
Upvotes: 1