Zachary King Zachary King - 5 months ago 33
Java Question

Split a String variable into a random substring with a specified length

In java.
It should use the random number generator to return a randomly chosen substring of text that has the specified length. If the length is either negative or greater than the length of text, the method should throw an IllegalArgumentException. For example, chooseSubstring("abcde", 4, new Random()) should return "abcd" about half the time and "bcde" about half the time.

public static String chooseSubstring (String text, int length, Random rand)
int randomNum = rand.nextInt(length);
String answer = text.substring(randomNum);
return answer;

Basically, I want to return a substring from the variable text. The substring must be the length of the variable length. The beginning of this substring should start at a random location determined by a random number generator. My problem is that the random number generator is not making sure the substring is the correct length.

System.out.println(chooseSubstring("abcde", 4, new Random()));

Should return
about the same amount of times. Instead it is returning:



Any info about how to solve this would greatly help thanks!

Answer Source

Your code is taking a substring at a random index between 0 and length, exclusive. You have to specify the end index so it doesn't extend to the end of the string. You also need to reduce the range of the starting index so the end index doesn't go past the string:

int randomNum = rand.nextInt(text.length() - length + 1);
String answer = text.substring(randomNum, randomNum + length);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download