Mastering arrays and loops, and ran into a problem. There are 2 arrays, with given random parameters. And during a loop, the parameter of each element of the array en []. Atk should be subtracted from each element of the array al []. + parameter al []. res. The loop works, but only in stage 1, after which it throws the error Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at Main.main (Main.java:22). I understand that I did not correctly refer to the 2 array, but I can not understand exactly how to correctly address it.
class Main { public static void main(String[] args) throws InterruptedException { Ally[] al = new Ally[3]; al[0] = new Ally("Hero One"); al[1] = new Ally("Hero Two"); al[2] = new Ally("Hero Three"); Enemy[] en = new Enemy[3]; en[0] = new Enemy("Enemy One"); en[1] = new Enemy("Enemy Two"); en[2] = new Enemy("Enemy Three"); System.out.println("Hero check \n"); for (int i=0; i < 3; i++){ System.out.println(al[i].name+ " HP = "+ al[i].hp+" Attack = "+al[i].atk+" Resist = "+al[i].res); } System.out.println(" "); System.out.println("Enemy check \n"); for(int i = 0; i < 3; i++){ System.out.println(en[i].name+ " HP = "+en[i].hp+ " Attack = "+en[i].atk+ " Resist = "+en[i].res); } System.out.println(" "); System.out.println("Battle begin \n"); for (int j = 0; j < al[j].hp; j++){ al[j].hp = al[j].hp - en[j].atk + al[j].res; System.out.println(al[j].name+ " HP = "+ al[j].hp+" Attack = "+al[j].atk+" Resist = "+al[j].res); Thread.sleep(1000); } } }