通过get方法比较ArrayLists扇区

时间:2015-12-14 16:31:31

标签: java arraylist methods get

我无法'弄清楚为什么我的代码不起作用,特别是它给我带来了ArrayList.get(i)== ArrayList.get(i)的问题;在Java中,它应该返回并比较这两个数字,这是不正确的?

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;

    }
}

1 个答案:

答案 0 :(得分:1)

在java中

  1. Integer是一个对象,而int是原始的。
  2. Collections(例如ArrayList)只能保留Object个而不能primitive数据
  3. 现在要比较两个对象的值,你必须使用equals(Object o)方法(注意==只比较参考) 所以当你说

    array.add(10); 
    

    这里10将转换为Object Integer然后被添加到数组中。

    所以在你的情况下检查相等性你应该有类似

    的东西
    userArray.get(i).equals(randomArray.get(i)