How to return 5 random “Powerball” numbers in Java

2019-07-04 04:44发布

Trying to return 5 random numbers between 1 and 42 in Java.

I currently have logic to return a single number (putting it into an ArrayList, but I'd like to do away with that.) I'm stumped on implementation to return 5 random numbers. Would I need 5 for loops?

    for (int i = 0; i < 10; i++) {
        int r = (int) (Math.random() * 42 + 1);
    }

I've seen some other related examples here and they seem more complex than what my needs dictate. However, I could be wrong.

7条回答
仙女界的扛把子
2楼-- · 2019-07-04 05:41

It's a straight forward approach.

   List<Integer> generated = new ArrayList<Integer>();
          for (int i = 0; i < 5; i++)
          {
              while(true)
              {
                 int r = (int) (Math.random() * 42 + 1);
                  if (!generated.contains(r))
                  {            
                      generated.add(r);
                      break;
                  }
              }
          }
查看更多
登录 后发表回答