2011-05-06 70 views
1

我有下面这个方法根据我的JSON条目的大小生成随机数,每个数字可能只会来一次。我投了3次这个方法,因为我需要生成3个随机数,这个数应该是相互不同的。Android:错误java.lang.IndexOutOfBoundsException无效的位置

有时它的工作原理,但有时它给我的logcat的这个错误:错误java.lang.IndexOutOfBoundsException无效位置 ,这让我的应用程序崩溃。

任何人都可以帮我解决我的问题吗?谢谢!

  int max = prjcts.size(); 
      List<Integer> indices = new ArrayList<Integer>(max); 
      for(int c = 1; c < max; ++c) 
      { 
       indices.add(c); 
      } 

      int arrIndex = (int)((double)indices.size() * Math.random()); 
      int randomIndex1 = indices.get(arrIndex); 
      indices.remove(arrIndex); 


      int randomIndex2 = indices.get(arrIndex); 
      indices.remove(arrIndex); 


      int randomIndex3 = indices.get(arrIndex); 
      indices.remove(arrIndex); 

@KPBird: 所以我改变我的代码就像你告诉我,但它仍然给我的错误soemtime: 我缺少的东西?

Random r = new Random(); 
    int arrIndex = r.nextInt(indices.size()); 
    int randomIndex1 = indices.get(arrIndex); 
    indices.remove(arrIndex); 


    int randomIndex2 = indices.get(arrIndex); 
    indices.remove(arrIndex); 


    int randomIndex3 = indices.get(arrIndex); 
    indices.remove(arrIndex); 

回答

3

indices.size() * Math.random()可能会返回列表的大小。这比上一个指数多一个。

所以你应该使用indices.size() - 1作为最大值。

5

问题是indices.remove(...)从列表中删除条目并在每次调用时将列表大小减1。另一个问题似乎是你试图为每个randomIndexX获得相同的数组索引,这没有任何意义。

编辑:完整的例子基于我下面的评论。这将以随机顺序打印出1到N(含)数字。

import java.util.ArrayList; 
import java.util.Collections; 
import java.util.List; 

public class RandomX { 

    public static void main(String[] args) { 
    int start = 1; 
    int n = 10; 
    List<Integer> numbers = new ArrayList<Integer>(); 

    for (int i = start; i <= n; i++) { 
     numbers.add(i); 
    } 

    Collections.shuffle(numbers); 

    for (int i = 0; i < n; i++) { 
     System.out.println(numbers.get(i)); 
    } 
    } 

} 
+0

因此,对我来说,每次调用方法时都会创建arrIndex2,arrIndex3并将其删除,这样会更好。我对么? – hectichavana 2011-05-06 08:55:59

+0

只需将数字放在索引中,调用Collections.shuffle(indices),然后取第一个X数字。随机播放会将它们随机分配给你。 – 2011-05-06 09:02:16

相关问题