-1

I couldn't' figure out why my code was not working, specifically it is giving me problems with the ArrayList.get(i) == ArrayList.get(i); in Java, it should return and compare the two numbers, is that not correct?

package homework.pkg9;

import java.util.ArrayList;
import java.util.Random;
import javax.swing.JOptionPane;

public class Homework9 {

    public static void main(String[] args) {

        //Create a method that creates a random winning lottery ticket
        //Ask the user to input his 5 numbers for the winning lottery
        //Make a mthode that campares the two arrays and return the numbers that match
        //If all numbers match generate the messge "Grand Prize Winner!"
        ArrayList userArray = new ArrayList();
        ArrayList randomArray = new ArrayList();
        ArrayList finalArray = new ArrayList();
        int userPick, counter = 0;

        randomArray = lottryNumbers();

        for (int i = 1; i <= 5; i++) {

            userPick = Integer.parseInt(JOptionPane.showInputDialog("Please choose a number between 0 and 9"));

            while (userPick <= 0 || userPick >= 9) {
                userPick = Integer.parseInt(JOptionPane.showInputDialog("Sorry, please choose a number between 0 and 9"));
            }

            userArray.add(userPick);
        }

        for (int i = 1; i <= 5; i++) {
            if (userArray.get(i) == randomArray.get(i)) {
                counter++;
                finalArray.add(userArray.get(i));
            }
        }

        if (finalArray.size() == 5) {
            System.out.println("Grand Prize Winner!");
        }

        System.out.println("Sorry, /n you only got these " + counter
                + " numbers correct: /n" + finalArray);
    }

    public static ArrayList lottryNumbers() {
        ArrayList randomArray = new ArrayList();
        Random rand = new Random();

        for (int i = 1; i <= 5; i++) {
            randomArray.add(rand.nextInt(10));
        }

        return randomArray;

    }
}
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Edon Freiner
  • 338
  • 2
  • 17

1 Answers1

1

In java

  1. Integer is an object while int is primitive.
  2. Collections(e.g. ArrayList) can only hold Objects and no primitive data

now to compare the values of two objects you must use equals(Object o) method (note == only compares the refrences) so when you say

array.add(10); 

in here 10 will be converted to an Object Integer then gets added to the array.

So in your case to check equality you should have something like

userArray.get(i).equals(randomArray.get(i)
nafas
  • 5,283
  • 3
  • 29
  • 57