+ 1

java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 20

what causes this error? Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 20 at keranjang.Basket.addCube(Basket.java:22) at Test.main(Test.java:8) import keranjang.Basket; public class Test { public static void main(String[] args) { Basket basket = new Basket(2500); basket.addCube(2); basket.addCube(3); basket.addCube(4); basket.addCube(5); basket.addCube(6); basket.removeCube(2); basket.removeCube(2); basket.addCube(3); basket.showBasket(); } } the other codes here https://codeshare.io/GArpxx

25th Sep 2019, 11:13 AM
ignacio
2 odpowiedzi
+ 1
you get error because incorrect calculate of volume return result higher than maxVolume, then public boolean addCube(float length) { if (cube.getVolume() < maxVolume) { //false !! so you do currentCube-- (0-1) instead add cube correct this and try result: public Cube(float squareSide) { ... // volume = (float) Math.pow(surfaceArea, 3); volume = (float) Math.pow(squareSide, 3);
25th Sep 2019, 5:37 PM
zemiak
+ 1
You are importing your own package!? If yes, then you write 2 times basket.removecube(2) If you want to remove index from list then it cause error because you are removing list index(2) two times. It gives you error because you are removing same index 2 times which is (2).
25th Sep 2019, 11:50 AM
Chirag Kumar
Chirag Kumar - avatar