You have been tasked with creating a random password generator program in Java. In order to accomplish this task, you decide to utilize the Random
class in Java.
Write a method named generatePassword
that takes in an integer length
as a parameter and returns a randomly generated password as a string. The password should meet the following criteria:
length
parameter.The method signature is:
public static String generatePassword(int length)
import java.util.Random;
public class RandomPasswordGenerator {
public static void main(String[] args) {
int passwordLength = 10;
String password = generatePassword(passwordLength);
System.out.println("Generated password: " + password);
}
public static String generatePassword(int length) {
Random random = new Random();
StringBuilder password = new StringBuilder();
// Generate at least one uppercase letter
password.append((char) (random.nextInt(26) + 'A'));
// Generate at least one lowercase letter
password.append((char) (random.nextInt(26) + 'a'));
// Generate at least one number
password.append(random.nextInt(10));
// Generate remaining characters
for (int i = 0; i < length - 3; i++) {
int randomType = random.nextInt(3);
switch (randomType) {
case 0:
password.append((char) (random.nextInt(26) + 'A')); // Uppercase letter
break;
case 1:
password.append((char) (random.nextInt(26) + 'a')); // Lowercase letter
break;
case 2:
password.append(random.nextInt(10)); // Number
break;
}
}
// Shuffle the password
for (int i = 0; i < length; i++) {
int randomIndex = random.nextInt(length);
char temp = password.charAt(randomIndex);
password.setCharAt(randomIndex, password.charAt(i));
password.setCharAt(i, temp);
}
return password.toString();
}
}
The solution above demonstrates how to generate a random password with the given length, as specified by the length
parameter. Here's a breakdown of the steps involved:
Random
class from the java.util
package, as it provides the necessary methods for generating random numbers.generatePassword
method that takes in an integer length
as a parameter and returns a string.Random
class using Random random = new Random();
.StringBuilder
object named password
to store the generated password.password.append((char) (random.nextInt(26) + 'A'))
), one random lowercase letter (password.append((char) (random.nextInt(26) + 'a'))
), and one random number (password.append(random.nextInt(10))
).length - 3
times to account for the already generated characters (one uppercase letter, one lowercase letter, and one number).generatePassword
method returns the generated password as a string using password.toString()
.In the main
method, we demonstrate th