Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

My numbers are matching but the code doesn't stop

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading