r/javahelp • • Jan 28 '20

Help with ArrayList and while loop

I'm trying to create a simple text-based RPG, and when they are not in danger, the player can inspect any items in their inventory, which I am using ArrayLists to keep track of. However, whenever I run this loop, it gives me a java.lang.IndexOutOfBoundsException. Can someone help?

if (InspectCheck == 1) {
    System.out.println("What item would you like to inspect?");
    int ItemRemaining = 0;
    int ItemToShow = ItemRemaining + 1;
        while (ItemRemaining <= Inventory.size()) {
		System.out.println("Select (" + ItemToShow + ") to inspect [" + 
                     + InventoryStr.get(ItemRemaining));
		ItemRemaining++;
		ItemToShow = ItemRemaining + 1;
	}
    ItemInspect()
}
17 Upvotes

8 comments sorted by

6

u/[deleted] Jan 28 '20

I’m not sure, but try to use ‘< inventory.size()’ instead of ‘<= inventory.size()’ in while condition

5

u/[deleted] Jan 28 '20

Thanks, that’s worked! It must be that because the ArrayList starts at 0, it counts them differently

5

u/wades39 Jan 28 '20

All data structures in java and in the vast majority of other languages start at zero, for your future reference.

3

u/[deleted] Jan 28 '20

Yes, that’s right ;)

6

u/wades39 Jan 28 '20

That's exactly the answer. The '.size()' method returns the maximum index + 1, which would be out of bounds as an index.

9

u/TheLegendOfTrain Jan 28 '20

Despite your problem being solved already, why dont you use a for-loop?

for (int i=0; i<Inventory.size(); i++){
    System.out.println("Select (" + (i+1)+ ") to inspect ["+InventoryStr.get(i));
}

Way less Code and more understandable in my opinion

0

u/[deleted] Jan 29 '20

[deleted]

3

u/TheLegendOfTrain Jan 29 '20 edited Jan 29 '20

Which is right. But you Do know how many Iterations you Do. You would use a while Loop when waiting for a Response from an instance you dont Control, e.g. A Server Response

Edit: better example: when you call a Method so long until you are in your conditions, but you cant predict the outcome of the Method.

1

u/Kanth0lz Feb 01 '20

He tried to give you a touch of something which you get a better understanding of by reading into "Big O Notation". For myself i think this page explains it in a pretty decent and simplified way. https://cooervo.github.io/Algorithms-DataStructures-BigONotation/big-O-notation.html (Nevertheless i have to criticize the O(n) example of "sorting an array via bubble sort" it's O(n) but just in the bestbest case; in education you will mostly try to assume the worst case)