Can someone please help me with coding the following in a single method: I need to randomaly generate 10 names between 3 and 10 characters long but each name only contains a single character e.g aaa, nnnnn etc;
I have the following code:
public static void task() {
// Chose Random character from below String
final String alpha = "abcdefghijklmnopqrstuvwxyz";
// Variable for max and min length of string
final int max = 10;
final int min = 3;
for (int n = 0; n < 10; n++) {
// Random select of length of the String
StringBuilder sb = new StringBuilder(alpha);
Random theGeneratorForLength = new Random();
int aLengthVariable = (theGeneratorForLength.nextInt(max - min) + min);
char alphaString = alpha.charAt(aLengthVariable);
sb.append(alphaString);
System.out.println("String " + (n + 1) + " :" + alphaString + aLengthVariable);
}
So I have alphaString which returns me a single chracter and then aLengthVariable which returns me the required lengths. Example output:
String 1 :f5
String 2 :d3
String 3 :h7
String 4 :h7
String 5 :d3
String 6 :i8
String 7 :j9
String 8 :i8
String 9 :j9
String 10 :e4
i am just struggling now to get the output to be the character repeated number of times it says so String 1 output would be fffff, String 2 ddd and so on.
>Solution :
Problem one, you are re-initializing your Random on every loop iteration. That resets the seed which is based on time by default. On a modern system, you’re likely to get the same seed over and over again. Declare it once before the loop. Second, you want to repeat the String a certain (random) number of times – and that is your count. You are using that as a random index into your "symbol table". Use the table length instead. Like,
public static void task() {
// Chose Random character from below String
final String alpha = "abcdefghijklmnopqrstuvwxyz";
// Variable for max and min length of string
final int max = 10;
final int min = 3;
Random rand = ThreadLocalRandom.current();
for (int n = 0; n < 10; n++) {
// Random select a "character" s.
String s = String.valueOf(alpha.charAt(rand.nextInt(alpha.length())));
// Random number of characters.
int count = rand.nextInt(max - min) + min;
System.out.println("String " + (n + 1) + " :" + s.repeat(count));
}
}