• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

please can you help to identify those errors

 
Nicholas Dintshi
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,from this code i do encounter some erros

class Array06
{
public static void main(String [] args)
{
int[][] arrayOfArray = new int[][];

int[] array1 = {10,20,30,40,50};
int[] array2 = {100,200,300};
int[] array3 = {5,10,15,20};

arrayOfArray[0] = array1;
arrayOfArray[1] = array2;
arrayOfArray[2] = array3;

int total = 0,noOfElements=0;

for(int i = 0;i<arrayOfArray.length;i++)
{
for(int j = 0;j<arrayOfArray[i].length;i++)
{
total += arrayOfArray[i][j];
noOfElements++
}
}

System.out.println("Total is:" + total);
System.out.println("Average:" + total/noOfElements);
}
}
 
fred rosenberger
lowercase baba
Bartender
Posts: 12196
35
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What are the errors? does it compile? does it run?
 
shilpa deshpande
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are two compile time errors.

1) Java needs all the dimensions of the array to be definite other than the last dimension. For example here, int[][] arrayOfArray = new int[3][];
will work beautifully.

2) There is a semicolon missing on line # 22.

One runtime error happens because in the loop on line # 19, instead of counter j, counter i is incremented which results in throwing the ArrayIndexOutOfBoundsException.

Tip: never copy the for loops, it takes hours to debug such small things.

The updated code looks like this.


Hope it helps
 
Anubhav Anand
Ranch Hand
Posts: 341
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nicholas Dintshi and Shilpa Deshpande,
Welcome to JavaRanch.

Nicholas please use code tags and other UBB tags as required. They make the post much more readable.

Hope you both have good time here. Good Luck..!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic