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.

1
  • 1
    username.equals(username[c]) is comparing a String[] with a String . Commented Nov 9, 2018 at 10:43

2 Answers 2

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.

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

Comments

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.");
        }
    }
}

3 Comments

Why not a Set if ordering is unimportant?
@vikingsteve I changed to set, but I thought the OP might want to preserve the order in which the usernames had been entered.
To preserve insertion order, a LinkedHashSet can be used. docs.oracle.com/javase/6/docs/api/java/util/LinkedHashSet.html

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.