Given the following requirements, write a Java code snippet that generates a random 6-digit password, using the Random class, with the following specifications:
Implement the following method:
/**
* Generates a random 6-digit password that meets the specified requirements.
*
* @return the randomly generated password
*/
public static String generatePassword() {
// your code here
}
Explain any assumptions, limitations, or design decisions you made while implementing the method.
The Random
class in Java provides methods to generate random numbers and can be used to fulfill the requirements of this problem.
Here's the implementation of the generatePassword
method:
import java.util.Random;
public class RandomPasswordGenerator {
public static void main(String[] args) {
String password = generatePassword();
System.out.println(password);
}
public static String generatePassword() {
Random random = new Random();
StringBuilder password = new StringBuilder();
// Generate a random uppercase letter
char uppercaseLetter = (char) (random.nextInt(26) + 'A');
password.append(uppercaseLetter);
// Generate a random lowercase letter
char lowercaseLetter = (char) (random.nextInt(26) + 'a');
password.append(lowercaseLetter);
// Generate a random digit
char digit = (char) (random.nextInt(10) + '0');
password.append(digit);
// Generate remaining random characters
for (int i = 0; i < 3; i++) {
char randomChar = (char) (random.nextInt(62) + 'a');
password.append(randomChar);
}
// Shuffle the password characters
for (int i = password.length() - 1; i > 0; i--) {
int j = random.nextInt(i + 1);
char temp = password.charAt(i);
password.setCharAt(i, password.charAt(j));
password.setCharAt(j, temp);
}
return password.toString();
}
}
Explanation:
Random
class to generate random numbers.StringBuilder
to build the password incrementally.(char) (random.nextInt(26) + 'A')
. This generates a random number between 0 and 25, which we add to the ASCII value of 'A' to get a random uppercase letter.password
StringBuilder.password
StringBuilder.password
. We iterate through each character starting from the last one, randomly swap it with another character using the setCharAt
method of StringBuilder
.Assumptions/Limitations/Design Decisions:
Random
class.