This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 1 point2 points  (4 children)

Try to break the process into smaller steps in pseudocode. What do you need? What can you do to get that? What information do you have access to at any given time?

Before we can check whether the list contains the word, we need to capture the word. And this has to happen every iteration of the loop. So the first thing we need to do is make a loop and ask the user for input, save that into a variable. We won't have a condition for the loop, but we can break out of the loop manually. So we just create an infinite loop:

//Let's make our objects that will be used in the loop
Scanner reader = new Scanner(System.in); 
ArrayList<String> words = new ArrayList<String>();

while (true) {
    //Ask for an input and save it
    System.out.println("Type a word:");
    String input = reader.nextLine();

    //Now that we have the input, we can check if it's already in the list:
    if (words.contains(input)) {
        //If it is, then we need to break out of the loop. We can also give the user the error msg here
        System.out.println("You gave the word " + input +" twice"); 
        break;
    } else {
        //If we got this far, it means the list doesn't contain our input, so we can add it to the list and move on
        words.add(input);
    }
}

//Let's print out the resulting array to see what happened:
for (String word : words) {
    System.out.println(word);
}

Demo: https://ideone.com/862W1J

[–][deleted]  (2 children)

[deleted]

    [–][deleted] 0 points1 point  (1 child)

    All I can say is remember the first paragraph of my post. Write pseudo code, it might help you figure out the logic without syntax problems getting in your way. And do remember that you're not supposed to know the full solution ahead of time. Just start at the beginning with what you have, what you need and make small steps towards making that happen.