comparing user inputs in array to make sure they dont have the same name in java

Viewed 26

What am I missing it keeps, coming back false on the first try. What do I need to change to make sure it scans to get rid of duplicates.

        final int numPassengers = 4;
        final int numShips = 2;
        boolean input = false;
        String[] travelerNames = new String[4];
        Scanner scanner = new Scanner(System.in);
        
        for(int i = 0; i < numPassengers; ++i) {
            System.out.println("Enter traveler name ");
            do {
                travelerNames[i] = scanner.nextLine();
                if(travelerNames[i].equals(travelerNames[i])) {
                    System.out.println("Names cannot match enter new name!");
                    input = false;
                    scanner.next();
                }
                else {
                    
                    input = true;
                }
            } while(!input);    
            System.out.println(travelerNames[i]);
2 Answers

A simple solution would be to use an arraylist. Arraylist has a method called contains.

    List<String> names = new ArrayList<>();
    Scanner scanner = new Scanner(System.in);
    String input = scanner.next();

    if(names.contains(input)){
        System.out.println("Name is duplicated");
    }
    else {
        names.add(input);
    }

I hope i could help you with your Problem

travelerNames[i] = scanner.nextLine(); Whoops... too late, it's already within the Array and it's in there before you get to check and see if it has been previously entered. Don't save a step here by popping the name into the Array right away, put the name into a String variable first then traverse the Array to see if that name already exists, for example:

for (int i = 0; i < numPassengers; ++i) {
    String name = "";
    while(name.isEmpty()) {
        System.out.print("Enter traveler name #" + (i + 1) + ": -> ");
        name = scanner.nextLine().trim();
        if (name.isEmpty() || name.matches("\\d+")) {
            System.out.println("Invalid Name Supplied! (" 
                             + name + ") Try again...\n");
            name = "";
            continue;
        }
        // Is the name already within the travelerNames[] Array?
        for (String nme : travelerNames) {
            if (nme != null && nme.equalsIgnoreCase(name)) {
                System.out.println("Invalid Entry! The name '" + name 
                         + "' already exists! Try again...\n");
                name = "";
                break;
            }
        }
    }
    // Everything seems OK so add the name to the Array.
    travelerNames[i] = name;
}
    
System.out.println();
System.out.println("The names contained within the Array:");
System.out.println(Arrays.toString(travelerNames));
Related