在单词中选择一个随机位置 - IllegalArgumentException?

时间:2013-07-04 17:12:50

标签: java random illegalargumentexception

此方法需要遵循以下步骤:

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 tricky point!)
   Swap the letters at positions j and i.
Print the word.

我的代码抛出 - IllegalArgumentException

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

我在这里堆叠,不知道如何规避这一点。

代码:

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 );
        }

我找不到Pick a random position j > i in the word. (this is tricky place!)的好解决方案。

  • 如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

该行

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

会抛出IllegalArgumentException加入参数&lt; = 0 ..

From nextInt Docs

  

抛出:       IllegalArgumentException - 如果n不是正数

在调用行

之前检查字符串的length

你可以这样做

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

答案 1 :(得分:0)

String word = "Example"
int len = word.length(); //len = 7
int placeHolder1 = (int) (Math.random() * length); //generates number between 0 and 6
int placeHolder2 = (int) 
int diff = length - placeHolder1;
placeHolder2 = (int) (Math.random() * diff + (length - diff + 1)); //Generates random between placeHolder1 and the length of the String 

这将为您提供String上两个字符的索引,您可以根据需要交换它们。