我无法'弄清楚为什么我的代码不起作用,特别是它给我带来了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;
}
}
答案 0 :(得分:1)
在java中
Integer
是一个对象,而int
是原始的。Collections
(例如ArrayList
)只能保留Object
个而不能primitive
数据现在要比较两个对象的值,你必须使用equals(Object o)
方法(注意==
只比较参考)
所以当你说
array.add(10);
这里10将转换为Object Integer
然后被添加到数组中。
所以在你的情况下检查相等性你应该有类似
的东西userArray.get(i).equals(randomArray.get(i)