Join Peggy Fisher for an in-depth discussion in this video Solution: Groceries, part of Learning Java 8.
- This challenge was designed to provide you with the opportunity to use ArrayLists and to get an idea of how to search for a specific item in an ArrayList. Let's take a look at my solution but remember, your solution might be very different. One of the things that you might have noticed with this solution is we had to do an import of both the java.util.ArrayList as well as the java.util.Scanner. So I started by creating an ArrayList of type string called groceries. Then I added five grocery items.
Bananas, wheat bread, 1% milk, crackers and oatmeal. The next thing I wanted to do was to present the list to the end user and ask them if they want to enter another item. I chose to allow them to enter another item or they could type in the word "quit" if they wanted to exit. I read in whatever value they typed. I needed a boolean variable called found so that I knew whether or not I found a match. I need you to scroll down now. My while loop is set up to compare whatever value they entered to the word quit.
If they entered quit, my while loop will not execute. But if they entered a valid item, I'm going to go into my loop and look for that item in my ArrayList. I search the entire ArrayList again using, newItem.equalsIgnoreCase so it doesn't matter whether they entered coffee with a little c or coffee with a capital C, I'll still find it. If I do find a match I tell them "This item is already in the list," and I set my found indicator to true. After my for loop, if my found indicator is false I add the item to the list.
And then I allow them to enter in another item. Or they can enter in \"quit"\ to exit. As soon as they enter \"quit"\ to exit, I go ahead and print out the final list. Okay, let's run this. It starts by providing the user with a current list. Now I can add another item. I'll add coffee to the list. Again, I get prompted if I want to add another item or if I want to \"quit"\ to exit. Let's enter an item that already exists, I'll enter oatmeal. It says the item is already in the list.
Okay, let's go ahead and quit. My final list added coffee to the end and you can see, it only added oatmeal one time from the original list. Okay, I hope this helped you to understand a little bit more about how to use an ArrayList and how to search an ArrayList. If you didn't get a chance to try it the first time, go back and try it on your own again.
- Downloading and exploring NetBeans
- Understanding Java basics: data types, strings, arrays, and more
- Controlling flow with functions and loops
- Creating classes
- Sorting and searching arrays
- Manipulating files
- Handling errors
- Building GUIs