-1

I'm trying to build a lottery program and I want to check if a number already exists in the previous winning numbers (inside the array). So I was trying this

int[] winningNumbers = new int[6]; //array holding 6 random numbers

for(i = 0; i < winningNumbers.length; i++ ){

    int randomNums = new Random().nextInt(49) + 1;

    while (Arrays.asList(winningNumbers).contains(randomNums)){
    System.out.println(Arrays.asList(winningNumbers).contains(randomNums));//always false 
    randomNums = new Random().nextInt(49) + 1;
    }
    winningNumbers[i] = randomNums ; 
    System.out.println(winningNumbers[i]);
}

Arrays.asList(winningNumbers).contains(randomNums) always was false regardless if the number exist or not so the while loop never was executed, so I solved it by writing a method

public static boolean findIfExist(int a[], int x){
   for (int i=0; i<a.length; i++){
      if (a[i]==x){
          return true;
      }
   }
    return false;
}

My question is why Arrays.asList(winningNumbers).contains(randomNums) always was false. What I'm doing wrong here?

Thanks for your time.

Andreas P.
  • 118
  • 9

1 Answers1

3

The problem lies in the interpretation of the varargs method Arrays.asList. It interprets the type to be int[], so that you receive back a List<int[]>, not a List<Integer>. So none of the numbers you pass in will be equal to an int[].

You could declare winningNumbers to be an array of Integers, so that the array will interpreted as you expect, and you receive a List<Integer> back. Your own findIfExist method works well also.

rgettman
  • 176,041
  • 30
  • 275
  • 357