Search code examples
javarandomillegalargumentexception

Pick a random position in the word - IllegalArgumentException?


I have to implement the following instructions (pseudocode):

Read a word.
Repeat word.length() times
   Pick a random position i in the word, but not the last position.
   Pick a random position j > i in the word. (this is a tricky point!)
   Swap the letters at positions j and i.
Print the word.

My code throws - IllegalArgumentException here:

j = i + 1 + generator.nextInt( word.length() - i - 1 );

I stack here and don't know how to circumvent this point.

Code:

public String scramble(String word) {
        Random generator = new Random(42);
        int x, i = 0, j = 0, wordLen = word.length();

        for (x = 0; x < wordLen; x++) {                
            i = generator.nextInt(wordLen);            
            j = i + 1 + this.generator.nextInt( word.length() - i - 1 );
        }

I can't find a good solution for this step:

Pick a random position j > i in the word.

  • How to solve this issue?

Solution

  • The line

    generator.nextInt( word.length() - i - 1 );
    

    would throw IllegalArgumentException incase the argument <= 0..

    From nextInt Docs

    Throws: IllegalArgumentException - if n is not positive

    Check the length of a string before calling the line


    You could do it this way

    for (x = 0; x < wordLen; x++) {
          i = generator.nextInt(wordLen - 1); 
          j = generator.nextInt(wordLen);           
          if (j <= i)
            j = i + generator.nextInt(wordLen - i);
    }