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);
System.out.println(chooseSubstring("abcde", 4, new Random()));
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);