Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

Java ArrayList contains method , small problem?

I am trying to prevent the user from entering a duplicate value for an arrayList , I think this is the correct way to do it. I believe its my if statement that does not work, I tried userNums.get(i).contains(userNums), but that will not work.

int i = 0;

while(i < 5)

{

System.out.println("\nEnter a number for the lottery, you may not enter a duplicate: ");

userNums.add(kb.nextInt());

if(!userNums.contains(userNums))

{

i++;

}

else{

System.out.println("You entered a duplicate number try again: ");

}

}

2 Answers

Relevance
  • 6 years ago
    Favorite Answer

    Try something like this instead:

    System.out.println("\nEnter a number for the lottery, you may not enter a duplicate: ");

    int x = kb.nextInt();

    if(userNums.contains(x)){

    System.out.println("Error");

    }

    else{

    userNums.add(x);

    i++;

    }

    }

    The reason your code doesn't work is because the method "contains()" is expecting an integer argument, not another ArrayList. Also, the way you have it set up, you would still need to remove the number after detecting the error. The way I have outlined, the check is done before adding the number to the ArrayList.

    Hope that helps!

  • ?
    Lv 4
    5 years ago

    Java Arraylist Contains

Still have questions? Get your answers by asking now.