Java 8 | Array & Random Practice — Lottery + Break

Student Kim
Buzz Code
Published in
3 min readJan 4, 2021

Hi y’all! Like I said last time, today let’s generate the lottery program. If you missed the first Array & Random Practice, the link is right on below!

[Question] Generate the lottery program by the following rules.

  1. Make an array to save 6 random numbers.
  2. Pick first 5 numbers from 1 to 52. There shouldn’t be same numbers.
  3. The last sixth one is the bonus number, pick it from 1 to 10.

Try to solve it by yourself, and the answer is on below!

I made an array named happyBall which has the length of 6. And I used the if statement to separate the first five numbers from the last bonus number. Then i declared the two variables to generate random numbers with the different range. And the reason why I added 1 on the each of the variable is to make the range of the random numbers start from 1 and finish at each 52 and 10.

But as you see there are same numbers coming out sometimes. Let’s fix that now.

I added another for statement to count the indexes before the index i. And check if there are same numbers with the rb in the array. If there is, make i get smaller so it can pick another rb again.

And here you would see the break; in the code, that means I’m going to end the current loop. In this case, the loop that break ends will be the second for statement which has the variable j.
Let’s say the i became 4 because of the first for statement, and the array looks like below.

If we got 9 as rb, it’s same with the value of the index [0], so the i will become 3 because of the i-- decrement. Here, we want the second for statement to be end, so the i can meet the i++ in the fist for statement and become 4 again! It’s a waste to check the back when we already found the same number in the first one.
So I used the break; to end the second loop when it finds the same value with the rb !

That’s all for today guys! I hope you all enjoyed to generate the lottery program. Next time let’s try to make the improved lottery program. Thanks guys, see ya!

--

--