我正在寻找帮助创建一个模拟彩票的随机数生成器。 编写生成5个随机兆数的方法的代码 数字范围。其中两个必须是偶数,其余三个 数字必须是奇数。使用模数运算符(%)检查数字是否为 偶数或奇数。请注意,不允许重复的数字,数字应介于1到50之间。 在一个单独的类中,我需要创建一个MegaBall编号,在启动时生成1-30之间的另一个随机数。
感谢任何帮助,提前致谢!
public class MegaBall {
public static void main(String[] args)
{
int[] lottoNumber = new int[5];
{`public class MegaBall {
public static void main(String[] args)
{
int[] lottoNumber = new int[5];
{
lottoNumber[0] = (int) ((50 * Math.random()) + 1);
lottoNumber[1] = (int) ((50 * Math.random()) + 1);
lottoNumber[2] = (int) ((50 * Math.random()) + 1);
lottoNumber[3] = (int) ((50 * Math.random()) + 1);
lottoNumber[4] = (int) ((50 * Math.random()) + 1);
}
System.out.print("Lottery Numbers: ");
for(int i=0; i<5; i++)
{
System.out.print(lottoNumber[i] + " ");
}
}
如何获得不同的2个偶数和3个奇数?
答案 0 :(得分:0)
拿这个,它有效:
import java.util.HashSet;
import java.util.Random;
/**
* Created by cullycross on 2/6/15.
*/
public class Lottery {
public static void main(String [] args) {
LittleLottery lottery = new LittleLottery();
lottery.showNums(lottery.getRandomNumbers());
lottery.showNums(lottery.getRandomNum());
}
static class LittleLottery {
private final int COUNT_OF_NUMS = 5;
private final int MAX_RANDOM = 50;
private final int MAXI_BALL = 30;
private final Random mRandom = new Random();
public Integer [] getRandomNumbers() {
HashSet<Integer> nums = new HashSet<>(COUNT_OF_NUMS);
for(int i = 0; i < COUNT_OF_NUMS; i++) {
Integer temp;
while (true){
temp = mRandom.nextInt(MAX_RANDOM) + 1;
if ((i + 1) % 2 == temp % 2
&& nums.add(temp)) {
break;
}
}
}
return nums.toArray(new Integer[COUNT_OF_NUMS]);
}
public Integer getRandomNum() {
return mRandom.nextInt(MAXI_BALL) + 1;
}
public void showNums(Integer... args) {
for(Integer i : args) {
System.out.println(i);
}
}
}
}