从指定的数字列表中生成两个数字
问题描述:
我想在指定的数字列表中生成两个数字。我写了这段代码,但它不起作用。任何人都可以提出一个更好的解从指定的数字列表中生成两个数字
public classl {
public static void main(String[] args) {
int[] lottery = new int[2];
int randomNum;
for (int i = 0; i < 3; i++) {
randomNum = (int) (Math.random() * (3,9,25,41,43,50,68)); // Random number created here.
for (int x = 0; x < i; x++) {
if (lottery[x] == randomNum) // Here, code checks if same random number generated before.
{
randomNum = (int) (Math.random() * (3,9,25,41,43,50,68));// If random number is same, another number generated.
x = -1; // restart the loop
}
}
lottery[i] = randomNum;
}
for (int i = 0; i < lottery.length; i++)
System.out.print(lottery[i] + " ");
}
}
}
答
您可以在这样一个数组存储这些数字:
int[] arr = {12, 13, 4, 7, 9};
然后得到一个随机数ARR阵列:
int rndNumber = new Random().nextInt(arr.length);
这是一些想法供你解决你的问题。
+1
我认为OP会比这更需要更多的帮助。 –
答
我想你问的是如何从集合中选择给定数量的随机元素。
如果这是正确的,那么你最好从一个集合而不是一个数组开始,因为集合中有很好的方法可以帮助你。这里有一些可能的方法:
List<Integer> theNumbers = Arrays.asList(3, 9, 25, 41, 43, 50, 68);
Random random = new Random();
// using uniqueness of sets
Set<Integer> results = new HashSet<>();
while (results.size() < 2)
results.add(theNumbers.get(random.nextInt(theNumbers.size()));
// using shuffle
Collections.shuffle(theNumbers);
List<Integer> results = theNumbers.sublist(0, 2);
// using streams (Java 8)
int[] results = random.ints(0, theNumbers.size())
.map(theNumbers::get).distinct().limit(2).toArray();
还有很多其他的方法,但希望这会让你开始。
答
sprinter的答案是优雅的做法。如果你很难理解它作为一个初学者,下面的例子将帮助你理解我们是如何做到这一点
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class LotteryGenerator {
public static void main(String[] args) {
//declare specified list of numbers
int[] lotteryBank = {3, 9, 25, 41, 43, 50, 68};
//get lottery numbers
int[] lottery = getLottery(lotteryBank);
System.out.println("The two lottery numbers are : [" + lottery[0] + ", " + lottery[1] + "]");
}
public static int[] getLottery(int[] lotteryBank) {
//find the total number of elements, so that random number generated is one among these
int indexRange = lotteryBank.length;
//create an array to hold two random numbers
int[] lottery = new int[2];
//create an instance of Random
Random r = new Random();
//create a set to hold two unique random numbers
Set<Integer> randomSet = new HashSet<Integer>();
//iterate till two unique random numbers are found
while(randomSet.size() != 2) {
//get a random index
int randomIndex = r.nextInt(indexRange);
//add the element at random index to the set
randomSet.add(lotteryBank[randomIndex]);
}
//convert random set to random array
int index = 0;
for(int x : randomSet) {
lottery[index++] = x;
}
return lottery;
}
}
注:我不鼓励使用INT []存储的彩票号码。实际上,不要使用原始数组,而是使用java提供的集合,它提供了很多实用程序方法,就像sprinter指出的那样。这个解决方案的目的只是为了告诉你如何做到这一点,你的方法倾向于
为什么在'Math.random()*'后面有逗号分隔的数字列表? –
为了回答您的问题并解决代码中的所有错误,我们基本上必须向您介绍Java编程语言。堆栈溢出不是地方的任务。 –