简体   繁体   English

使用 math.random 和 while 循环的简单 Java 彩票模拟器?

[英]Simple Java lottery simulator using math.random and while loop?

How would i format a while loop to check for duplicates and if there is a duplicate, to not return that number(s)?我将如何格式化 while 循环以检查重复项,如果有重复项,则不返回该数字?

 import java.util.Scanner;

public class LotterySimulator 
{
   public static void main(String[] args)
   {
      final int POOL1 = 68;
      final int POOL2 = 25;

      long ball1, ball2, ball3, ball4, ball5, pball;

      ball1 = Math.round(POOL1*Math.random()) + 1;
      ball2 = Math.round(POOL1*Math.random()) + 1;
      ball3 = Math.round(POOL1*Math.random()) + 1;
      ball4 = Math.round(POOL1*Math.random()) + 1;
      ball5 = Math.round(POOL1*Math.random()) + 1;
      pball = Math.round(POOL2*Math.random()) + 1; 

You can use Set collection to store unique values.您可以使用 Set 集合来存储唯一值。 Method add() return true if this set did not already contain the specified element如果此集合尚未包含指定元素,则方法add()返回true

For example:例如:

    public static void main(String[] args) {
        final int POOL1 = 68;
        final int POOL2 = 25;

        int i = 0;
        Set<Long> ballSet = new HashSet<>();
        while (i < 5) {
           long ball = Math.round(POOL1 * Math.random()) + 1;

           if (!ballSet.add(ball)) {
               continue;
           };
           i++;
        }
        long pball = Math.round(POOL2 * Math.random()) + 1;
        while (ballSet.contains(pball)) {
            pball = Math.round(POOL2 * Math.random()) + 1;
        }
        String winner = ballSet.stream().map(Object::toString).collect(joining(", "));
        System.out.println("Your winning numbers are: " + winner);
        System.out.printf(" and the powerball is: %d", pball);
    }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM