2014-04-28 126 views
0

我想在android中重新生成随机数字。我想生成两个可以彼此整除的数字。如果生成的数字不可分割,我希望系统再次尝试,直到它生成可彼此整除的数字。重新生成随机数。 Android的?

这里是我的代码:

Random random = new Random(); 
      arrone = random.nextInt(100 - 20) + 20; 

      Random randm = new Random(); 
      arrtwo = randm.nextInt(11 - 2) + 2; 

      if (arrone % arrtwo ==0){ 

      // if they are divisible do this. 

      } else { 
      // if they are not divisible, I want it to try again and find two divisble numbers 

      } 

回答

0
boolean divisible = false; 
    while (!divisible) { 
     Random random = new Random(); 
     arrone = random.nextInt(100 - 20) + 20; 

     Random randm = new Random(); 
     arrtwo = randm.nextInt(11 - 2) + 2; 

     if (arrone % arrtwo == 0){ 

      // if they are divisible do this. 

      divisible = true; 
     } 
    } 
} 
3

要改写这个问题,你想两个数字,其中一个是另一个的倍数。重要的区别是您不需要使用循环来查找这样的一对值。

int min = 20; 
int max = 100; 
int second = rand.nextInt(11 - 2) + 2; 
int multiplier = Math.max((min + second-1)/second, 
          rand.nextInt(max/second) + 1); 
int first = multiplier * second; 

在这种情况下,你知道第一个必须被第二个整除。