0
Please help me with the errors in the program
class a { public static void main(String []args) { //int arr[][]; int arr = new int[2][4]; arr[0][1]=1; arr[0][2]=2; arr[0][3]=3; arr[0][4]=4; arr[1][1]=11; arr[1][2]=22; arr[1][3]=33; arr[1][4]=44; for(int i=0;i<2;i++) { for(int j=0;j<5;j++) { System.out.println(arr[i][j]); } System.out.println("/n"); } } }
4 odpowiedzi
+ 1
You cannot access arr[0][4] aswell as arr[1][4] You have to start both indexes at 0 so the biggest index for your second [] is 3.
Then you have to edit the condition of your inner for loop to j<4
0
class a
{
public static void main(String []args)
{
//int arr[][];
int[][] arr= {{1,2,3,4},{11,22,33,44}};
for(int i=0;i<2;i++)
{
for(int j=0;j<4;j++)
{
System.out.print(arr[i][j]);
}
System.out.println("\n");
}
}
}
0
I solved it thanks..
0
Array index should always start from 0 and the upper limit for an array index of array length 4 should be 3, not 4.
So,
arr[0][0] = 1;
arr[0][1] = 2;
.
.
.
The same goes to the second inner nested loop, it should be 4 because the index for the 2nd dimension index is 0-3.