Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic Java ArrayList: Gift List. The code works and is displaying the desired output but I would like to understand more?

Tags:

java

arraylist

I'm a beginner in Java and I've only just started self-studying on Arrays and Lists. The following are snippets of the code I came up with for the Gift Registry exercise online and while I understand most of it, there were times when I had to do trial and error until the code finally displayed my desired output. Here are a couple of questions:

System.out.println("Enter item: ");
gift.add(x.next()); 
System.out.println("Enter store: ");
store.add(x.next());

This is the code for when the user enters a gift and the store from which he can purchase it from. I discovered that if I entered words separated by spaces, the output would look like this:

Do you wish to make a gift wish list? [Y/N]
Y
Enter item: 
High heels
Enter store: 
Any more items? [Y/N]

Question #1: Why does this happen? I declared early on in the code that this was a String (an ArrayList, but a <String>), and even when I modified the Scanner method to (x.nextLine()); I would still get this printed in the console. When the user enters a one-word answer, the code works just fine, but I still want to know why this happens, and what a possible alternative would be that would allow entries with spaces.

Question #2: This part of the code, I had to look up on the internet. There weren't any explanations as to why this was what's required, but the code worked anyway.

for (int i = 0; i < gift.size(); i++) {
    System.out.print(gift.get(i)+ " - ");
    System.out.print(store.get(i));
    System.out.println("");
}

Before I found this, I initially started with System.out.println("Gift List: \n" + gift + " - " + store); and while the user-input items were displayed, they were in brackets and separated by commas. What is the value of i in this code and why did we increment it? I also tried to change the gift in gift.size(); to store and the code still worked fine. Why is that, by the way? Do we just choose which variables to put or is there a certain syntax to follow?

Thanks in advance.

EDIT: Here's the full code.

package arrays;

import java.util.ArrayList;
import java.util.Scanner;
public class GiftList {

    public static void main(String[] args) {
        Scanner x=new Scanner (System.in);

    char ans;
    ArrayList<String> gift= new ArrayList<String>();
    ArrayList<String> store = new ArrayList<String>();

        System.out.println("Do you wish to make a gift wish list? [Y/N]");
            ans=x.next().toLowerCase().charAt(0);

        while (ans!='n')

        {
            System.out.println("Enter item: ");
            gift.add(x.nextLine());
            System.out.println("Enter store: ");
            store.add(x.nextLine());

            System.out.println("Any more items? [Y/N]");
            ans=x.next().toLowerCase().charAt(0);
        }

        System.out.println("Gift List: ");
        for (int i = 0; i < gift.size(); i++) {
            System.out.print(gift.get(i)+ " - ");
            System.out.print(store.get(i));
            System.out.println("");
        }
    }

}
like image 492
braindead Avatar asked Nov 19 '25 20:11

braindead


2 Answers

Question 1:

You skip over the items list because x still contains a newline character, calling x.nextLine() prior to adding your item will fix this:

while (ans!='n'){
    x.nextLine(); //Skip the enter keypress
    System.out.println("Enter item: ");
    gift.add(x.nextLine());
    System.out.println("Enter store: ");
    store.add(x.nextLine());

Adding gifts with spaces works, once you fix up the loop.

Do you wish to make a gift wish list? [Y/N]y

Enter item: high heels

Enter store: mine

Any more items? [Y/N] n Gift List: high heels - mine

Question #2: This part of the code, I had to look up on the internet. There weren't any explanations as to why this was what's required, but the code worked anyway.

for (int i = 0; i < gift.size(); i++) {
        System.out.print(gift.get(i)+ " - ");
        System.out.print(store.get(i));
        System.out.println("");
    }

This is a standard for loop. i acts as a counter for each of the items in the list. gift.size() returns an integer value for how many items are within the list, i++ uses the current value of i and then increments it at the completion of the loop.

Because i gets incremented on every iteration of the loop a call to gift.get(i) will return the value stored at index i. So on the first iteration i=0, on the second i=1, third i=2 and so on.

As for why it's required - it's not the only method that will work, you could do a few different things to make it work the same. Although Personally I find the standard for loop easy to understand in examples like this.

The key to this part of code those is your call to store.get(i) This call gets the same index as gift.get() and will return the same position in the list.

I'm not sure what the relation to store and gift are, but it would seem that a HashMap may be a better collection. A HashMap is a collection of Key,Value pairs.

Sometimes it makes more sense to organize your values in a K,V relationship rather than in two separate collections. For instance, with a hashmap you would have a store->gift relationship and can then iterate over the collection displaying values. Check the linked docs for some examples of usage.

However that being said it may be best to wait for hashmaps until your get the relevant section in the book your working through, otherwise you may confuse yourself on the examples.

I think Question 1 needs some more information before we can properly explain why it didn't work as expected. Can you post the surrounding code?

like image 152
Robert H Avatar answered Nov 21 '25 09:11

Robert H


Answer to Question 2 :

When you pass an Object to the method System.out.println(Object obj), it will use the method toString() of the Object obj to display it. In this case, the object you display is an ArrayList, so it will use the toString() of the Object ArrayList (actually it will use the toString() method of AbstractCollection because ArrayList extends this class).

The second way to print the elements of a List is to run through it with a loop (here a for loop). So you need a variable (here i) to go to each elements contained in your list).

like image 43
Patrick Avatar answered Nov 21 '25 09:11

Patrick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!