2

Newbie here.

I just want to ask, how to disallow someone to enter the same element in an array?

this is my code currently and it's not working properly:

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        String[] username=new String[5];    
        for (int c=0;c<5;c++)
    {
        System.out.print("Enter client name: ");
        username[c]=input.nextLine();
        if (username.equals(username[c]))
        {
            System.out.println("The client already exist.");
        }
    }
    }
}

p.s. I hope you guys can help me.

2 Answers2

2

Try using a data structure such as a set, which makes it easy to determine if a certain username be already present:

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    Set<String> users = new HashSet<>();

    while (users.size() < 5) {
        System.out.print("Enter client name: ");
        String username = input.nextLine();

        if (!users.add(username)) {
            System.out.println("The client already exist.");
        }
    }
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
2

While you can use an array to handle this problem in java there is a data structure that handle your problem very easily.

This data structure is a Set:

A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56