Exit Exit - 2 years ago 81
Java Question

More than once in an arrayList with user input

In the code below I need to check if a number appears more than once in an

. The user inputs a number to consult, and if it exist in the
and there are more than one the messages, "appears more than once is displayed". I have been trying to do this but I don't know how.

This is the

ArrayList<Integer> list = new ArrayList<>();

System.out.println("Type a number: ");
int number = Integer.parseInt(sc.nextLine());
if (Metodos.moreThanOne(list, number)) {
System.out.println(number + " appears more than once.");
} else {
System.out.println(number + " does not appear more than once.");

This is the method:

public static boolean moreThanOne(ArrayList<Integer> list, int number) {
for (Integer in : list) {
if (list.contains(number) && in==in) {
return true;
return false;

Answer Source

You can use this code:

if (list.lastIndexOf(element) != list.indexOf(element)) {
  return true; // you have at least two numbers
} else {
  return false; // element is not exist or you have only one element
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download