Matthew Matthew - 1 year ago 67
Java Question

Item List for Text RPG

I'm trying to make a simple text-based RPG to keep my skills sharp between semesters. I'm trying to create the different elements separately before bringing them together. Right now, I'm trying to create a basic generic list to hold "Item" objects for the player (things like potions and bombs etc.).

enter image description here

As you can see in the image, I'm trying to tie the index values to the individual items in the list. Since I added the same item to the list three times, it shows up three times (which is what I want), but I'm wondering how I can have this and somehow have the index value represent that actual number of items instead of just the true index value of the objects added.

Essentially, I want to be able to have the player select a number and then use the item that way. I'm sure I'm missing something obvious, I appreciate any insight!

Answer Source

Use a for loop instead of a for-each loop so you have access to a counter.

for (int i = 0; i < playerItems.size(); i++)
    System.out.println(i + ". " + playerItems.get(i).getName());

Or, just use the ctr variable you already have and increment for each item.

for (Item i : playerItems)
    System.out.println(ctr + ". " + playerItems.get(i).getName());

Also, you don't need to check if playerItems contains i. You will never get an item in a for-each loop that isn't in the collection.