I need to create a random string which should be between the length of 6 to 10 but it sometimes generates only about the length of 3 to 5.
Here’s my code. Can anyone would be able to find out the problem? 🙁
int lengthOfName = (int)(Math.random() * 4) + 6;
String name = "";
/* randomly choosing a name*/
for (int j = 0; j <= lengthOfName; j++) {
int freq = (int)(Math.random() * 100) + 1;
if(freq <= 6){
name += "a";
}if(freq == 7 && freq == 8){
name += "b";
}if(freq >= 9 && freq <= 11){
name += "c";
}if(freq >= 12 && freq <= 15){
name += "d";
}if(freq >= 16 && freq <= 25){
name += "e";
}if(freq == 26 && freq == 27){
name += "f";
}if(freq == 28 && freq == 29){
name += "g";
}if(freq >= 30 && freq <= 33){
name += "h";
}if(freq >= 34 && freq <= 48){
name += "i";
}if(freq == 49 && freq == 50){
name += "j";
}if(freq >= 51 && freq <= 55){
name += "k";
}if(freq >= 56 && freq <= 60){
name += "l";
}if(freq == 61 && freq == 62){
name += "m";
}if(freq >= 63 && freq <= 70){
name += "n";
}if(freq >= 71 && freq <= 75){
name += "o";
}if(freq == 76 && freq == 77){
name += "p";
}if(freq == 78){
name += "q";
}if(freq >= 79 && freq <= 84){
name += "r";
}if(freq == 85 && freq == 86){
name += "s";
}if(freq == 87 && freq == 88){
name += "t";
}if(freq >= 89 && freq <= 93){
name += "u";
}if(freq == 94){
name += "v";
}if(freq == 95 && freq == 96){
name += "w";
}if(freq == 97){
name += "x";
}if(freq == 98 && freq == 99){
name += "y";
}if(freq == 100){
name += "z";
}
}
I’m sorry but the code is too poorly written to be salvageable. I recommend something like this.
Key points are:
java.util.Random, specificallynextInt(int n)to get a randomintin a given rangeStringBuilder.charAtto index its letters.API links
java.util.Randomint nextInt(int n)StringBuilder– A mutable sequence of characters.Related questions
Problems with the original code
There are plenty, unfortunately.
String +=in a loop yields very poor performance for longer stringsfor (int j = 0; j <= lengthOfName; j++)is an off-by-one-errorfreq == 7 && freq == 8is a logical contradictionI highly recommend doing lots of small but simple exercises to learn Java basics. codingbat.com is great; it has hundreds of these, they’re automatically graded so you’ll know when your solution works as expected or not. It has sections on logic, strings, arrays, etc.
On uneven letter distribution
The simplest solution is to just have duplicates in the alphabet:
String alphabet = "aab";will have probability foratwice as much asbalphabetprogrammatically from a frequency table