4

I have looked in many places online and all seem to give me the same solution. So it's obvious that I have made some sort of silly mistake I cannot see. Can someone please point me in the right direction. Thanks a mill.

Here is my code:

import java.util.Arrays;

public class Solution { 
    public static void main(String[] args) {
        int[] outcomes = {1, 2, 3, 4, 5, 6};        
        int count = 0;      
        for(int y = 1; y<=6; y++){      
            if(Arrays.asList(outcomes).contains(y)){                
                count++;                
                System.out.println("outcomes contains "+ y);                
            }               
        }           
        System.out.println(count);  
    }

The final output should be 6 but it is 0.

1
  • This is similar to this question Commented Nov 4, 2014 at 12:05

2 Answers 2

6
Arrays.asList(int[])

returns a single-element list. The one element is the int[] you have passed in.

If you change the declaration

int[] outcomes

to

Integer[] outcomes

you'll get the expected result.

Sign up to request clarification or add additional context in comments.

Comments

0

Two things should be corrected in your code:

  1. Changing int[] to Integer[] (as sugested Marko Topolnik in previous answer)
  2. Moving Arrays.asList befor for loop. Now array is converted to list 6 times.

After this changes code will look as follows:

public static void main(String[] args) {

    Integer[] outcomes = {1, 2, 3, 4, 5, 6};
    List outcomesList = Arrays.asList(outcomes);
    int count = 0;

    for(int y = 1; y<=6; y++){
        if(outcomesList.contains(y)){
            count++;
            System.out.println("outcomes contains "+ y);
        }
    }
    System.out.println(count);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.