I am developing a password generator program. Here you can set the percentage of numbers, letters and special characters you want to have in your password, as well as the size of your password. Later I concatenate the numbers, letters and symbols and I need to shuffle them so that it looks like a password (this was the best solution I found to generate passwords following this percentage character concept).
The problem is that I need to shuffle an array of characters at random.
This array can be an array of char
, or even a String
, the important thing is that I have to print this on the screen in a scrambled form later.
Searching a little, I found the function shuffle();
of class Collecions
and wrote the following code, which does exactly what I want:
public static String shuffleString(String s) {
List<String> letters = new ArrayList<String>();
String temp = "";
for (int i = 0; i < s.length(); i++) {
letters.add(String.valueOf(s.charAt(i)));
}
System.out.println("");
Collections.shuffle(letters);
for (int i = 0; i < s.length(); i++) {
temp += letters.get(i);
}
return temp;
}
The problem is that I find this code a bit "heavy". I think there must be some simpler way of doing this. I've also been worried about how these items are shuffled, as I need something random, or as random as possible.