-1

I'm an amateur coder who just started coding and I was making a kind of lottery system which should have kept repeating till the ticket was equal to the random numbers, but it didn't stop even though the numbers matched.

import java.util.Arrays;
import java.util.Random;

public class luckyLotteryTest {

    public static void main(String[] args) {
        // The code below will assign random numbers to the three 'winning number'.
        Random randomGenerator = new Random();
        int[] luckyNumbers = new int[3];
        luckyNumbers[0] = randomGenerator.nextInt(3) + 1;
        luckyNumbers[1] = randomGenerator.nextInt(3) + 1;
        luckyNumbers[2] = randomGenerator.nextInt(3) + 1;

        /* The values of the numbers below need to be changed by numbers of your choice.
           But their values must be between one and three. */
        int[] myLotteryTicket = new int[3];
        myLotteryTicket[0] = 3;
        myLotteryTicket[1] = 2;
        myLotteryTicket[2] = 1;

        while (myLotteryTicket != luckyNumbers) {
            System.out.println(Arrays.toString(luckyNumbers));
            luckyNumbers[0] = randomGenerator.nextInt(3) + 1;
            luckyNumbers[1] = randomGenerator.nextInt(3) + 1;
            luckyNumbers[2] = randomGenerator.nextInt(3) + 1;
        }
    }
}

Could someone please tell me what I did wrong?

tobias_k
  • 81,265
  • 12
  • 120
  • 179
  • 2
    Don't use `!=` to compare Arrays, but [`Arrays.equals`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#equals(int%5B%5D,int%5B%5D)) – tobias_k Jul 28 '22 at 08:04
  • 1
    `myLotteryTicket != luckyNumbers` compares the array references, not their actual content. See `Arrays.equals`. – m0skit0 Jul 28 '22 at 08:06

1 Answers1

1

Java arrays are objects, so using == or != will just compare the reference, not the content. For this, you should use Arrays.equals, i.e.

while (! Arrays.equals(myLotteryTicket, luckyNumbers)) {
    System.out.println(Arrays.toString(luckyNumbers));
    luckyNumbers[0] = randomGenerator.nextInt(3) + 1;
    luckyNumbers[1] = randomGenerator.nextInt(3) + 1;
    luckyNumbers[2] = randomGenerator.nextInt(3) + 1;
}
tobias_k
  • 81,265
  • 12
  • 120
  • 179