2012-09-20 21 views
1

我已经设置了一个任务来创建一个Android应用程序,用户在其中选择四个数字(1-6),然后将其与四个随机生成的数字进行比较,然后告诉他们有多少个数字是正确的。Java/Android偏向号码发生器

我的问题是,每当我生成任何数字的前三个显示是总是相同,除了从最后一个数字。

Random a1 = new Random(); 
    random1 = new ArrayList<Integer>(); 

    for (int index = 0; index < 6; index++) 
    { 
     random1.add(a1.nextInt(5)+ 1); 
    } 

    Random a2 = new Random(); 
    random2 = new ArrayList<Integer>(); 

    for (int index = 0; index < 6; index++) 
    { 
     random2.add(a2.nextInt(5)+ 1); 
    } 

这是我使用的随机数生成的代码,每个数字使用完全相同的代码,这使得它更加混乱,如果他们都是一样的,我可以理解,因为它是相同的代码,它会沿着这些线条生成相同的数字或者其他东西,但最后一个总是不同的,任何帮助总是会被赞赏的。

回答

0

尝试不创建两个随机实例,而是重复使用单个实例。可能是两个关闭种子的Randoms产生密切的产量。

+0

默认随机对象使用该方法'这个(++ seedUniquifier + System.nanoTime());' –

+0

好吧,我将修改我的答案 –

+0

我的想法是,让我改变了所有的随机数用“ a1',但是我得到'[4,4,5,5]'的输出很奇怪? – 8BitSensei

0

检查下面的代码是否适合您。代码取自http://www.javapractices.com/topic/TopicAction.do?Id=62。根据您的要求修改。

public final class RandomRange { 

public static final void main(String... aArgs) { 

    int START = 1; 
    int END = 6; 
    Random random = new Random(); 
    List<Integer> first = new ArrayList<Integer>(); 
    List<Integer> second = new ArrayList<Integer>(); 
    for (int idx = 1; idx <= END; ++idx) { 
     first.add(showRandomInteger(START, END, random)); 
     second.add(showRandomInteger(START, END, random)); 
    } 
    System.out.println(first); 
    System.out.println(second); 
    first.retainAll(second);//Find common 
    System.out.println(first); 

} 

private static int showRandomInteger(int aStart, int aEnd, Random aRandom) { 
    if (aStart > aEnd) { 
     throw new IllegalArgumentException("Start cannot exceed End."); 
    } 
    // get the range, casting to long to avoid overflow problems 
    long range = (long) aEnd - (long) aStart + 1; 
    // compute a fraction of the range, 0 <= frac < range 
    long fraction = (long) (range * aRandom.nextDouble()); 
    int randomNumber = (int) (fraction + aStart); 
    return randomNumber; 
} 

}