Java, I get a index out of bounds exception with this method, can you spot where the method goes out of bounds from this code?
public void showEarliestAttack(){ String earliestAttack; for (int i = 0; i < attackArray.size(); i++) { earliestAttack= attackArray.get(i).toString(); if(attackArray.get(i+1).getDate().compareTo(attackArray.get(i).getDate())<0){ earliestAttack = attackArray.get(i+1).toString(); } System.out.println(earliestAttack); } }
public void showEarliestAttack() { String earliestAttack; for (int i = 0; i < attackArray.size() - 1; i++) { // only iterate until size-1. because you are accessing i+1 element in the loop body earliestAttack = attackArray.get(i).toString(); if (attackArray.get(i + 1).getDate().compareTo(attackArray.get(i).getDate()) < 0) { earliestAttack = attackArray.get(i + 1).toString(); } System.out.println(earliestAttack); } }
Get Answers For Free
Most questions answered within 1 hours.