lundi 25 septembre 2017

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 abcd and bcde about the same amount of times. Instead it is returning: bcde cde de abcde. Any info about how to solve this would greatly help thanks!




Aucun commentaire:

Enregistrer un commentaire