0

Multi-dimensional Arrays Out of Bounds

My code is telling me that "Index 2 out of bounds for length at line 9," Can someone tell me why this error is happening? package practiceClasses; public class FunArrays { public static void main(String[] args) { int pHealth [] [] = { {1,2,3},{1} }; pHealth[0][0] = 100; pHealth[1][0] = 75; pHealth[2][0] = 75; System.out.println(pHealth[2][0]); } }

23rd Aug 2021, 3:16 PM
William Davis
William Davis - avatar
4 Respostas
+ 3
<pHeealth> has only 2 rows, index 0 and 1. An attempt to access index 2 is impossible. What you intend to do actually?
23rd Aug 2021, 3:21 PM
Ipang
+ 1
Ipang I was making it as if there are 3 players and 3 different healths. If the [] [] [] are the rows and 1,2,3 are the columns, what is that extra 1?
23rd Aug 2021, 4:00 PM
William Davis
William Davis - avatar
+ 1
Ipang Still new to Java, I was thinking that the [][] set 2 areas, 1 for the players and 1 for health. Then, the 1,2,3 I was thinking was for each player. Finally, the 1 was for health.. clearly I'm still a little confused about arrays. (Reason I quit last time, hoping that won't happen this time)
23rd Aug 2021, 4:31 PM
William Davis
William Davis - avatar
0
If I understood you correctly, it seems you wanted to set player 1 health to 100, second and third player health to 75. If this was your intention then you could do pHealth[0][0] = 100; pHealth[0][1] = 75; pHealth[0][2] = 75; The three lines above updates all column values at row 0. TBH I'm not getting the idea why you have created that second row, which contains {1}.
23rd Aug 2021, 4:11 PM
Ipang