The problem I am getting is that whenever I use powerItem this error pops up. Exception in thread “main” java.lang.IndexOutOfBoundsException: Index 10 out of bounds for length 1.However when I use HealthItem it heals health properly.
I tried to do change index of powerIndex but it doesnt work only the HealthIndex is working properly. I was expecting that when I use healthItem it should restore health which it does but the powerItem doesnt and causes an error.Here is my code:
`public void displayInventory(Characters objCharacters){
if(inventoryForHealth.isEmpty() && inventoryForPower.isEmpty()) {
System.out.println("nYour inventory is empty.");
}else {
while(true) {
System.out.println("Select The Item");
System.out.print("0. Exit Inventory, ");
index = 1;
for (String string : inventoryForHealth) {
System.out.print(index+". "+string+", ");
index++;
}
for (String string2 : inventoryForPower) {
System.out.print(index+". "+string2+", ");
}
selectItem = obj.nextInt() ;
healthIndex = selectItem - 1;
powerIndex = selectItem - 1 - inventoryForHealth.size();
if(selectItem == 0){
return;
}
if(selectItem > 0 && selectItem <= inventoryForHealth.size()) {
removeHealthItem(healthIndex);
if(health >= maxHealth) {
System.out.println("Health is already full.");
}
break;
}else if(selectItem > inventoryForHealth.size() && selectItem <= (inventoryForHealth.size() + inventoryForPower.size()) ){
removePowerItem(powerIndex);
if (power >= maxPower) {
System.out.println("Power is already full.");
}break;
}else {
System.out.println("nInvalid Choice");
}
}
}
}`
These are the otherMethods used in this
public void removeHealthItem(int index) { if(index >= 0 && index < inventoryForHealth.size() && health < maxHealth) { int healingPoints = healthHealPoints.get(index); healHealth(healingPoints); inventoryForHealth.remove(index); healthHealPoints.remove(index); } } public void removePowerItem(int index) { if(index >= 0 && index <= inventoryForPower.size() && power < maxPower) { int healingPoints2 = powerHealPoints.get(index); healPower(healingPoints2); inventoryForPower.remove(index); powerHealPoints.remove(healingPoints2); } }
Minecraft Survivalist is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.