mercredi 10 avril 2019

How do I prevent duplicates from being added to ArrayList using conditional statement? Java (aka no Hash set etc)

Im nearly finished with a program that gathers user's inputs (keywords) and displays them. I have it functioning in that regard but I also need to prevent duplicate keywords from being added to the List using a conditional if statement. I know I'm on the right track (see commented code), but having trouble wrapping my mind around the syntax and use of a boolean to compare the entered keyword with the existing arrayList.

I know there are methods such as Hash/Set but I'd like to be able to do it with the conditional statement before I move onto other techniques. Every answer I've found in the search seems to explain use of Hash.

Thanks!

import java.util.*;

public class KeywordData {
    private ArrayList<Keyword> keywords = new ArrayList<Keyword>();

    public void create() {
        InputHelper inputHelper = new InputHelper();
        String prompt = "";
        boolean isTrue = true;

        while (isTrue) {
            prompt = inputHelper.getUserInput("Enter a string, otherwise type 'n' to exit:");
            if (!prompt.equals("n")) {
                Keyword keyword = new Keyword();
                keyword.setUserKeyword(prompt);

                ////////////////////////////////////
                // Using/Altering the code in place below, how to check if the entered keyword is already in 
                // the array list and subsequently not add it to the List???
                boolean alreadyExists = false;
                for (Keyword keyword1 : keywords) {
                    if () {

                    }
                }
                keywords.add(keyword); // if Key already exists, don't add to array list. 
                ///////////////////////////////////

            } else {
                break;
            }
        }
    }

    public void displayKeywords() {
        System.out.println();
        System.out.println("********** Your unique user keywords **********");
        for (Keyword keyword : keywords) {
            keyword.display();
        }
        System.out.println();
    }

}

Aucun commentaire:

Enregistrer un commentaire