swydell swydell - 3 months ago 5
Java Question

Multidimensional arrays with enhanced for loop in java printing to the command line

I'm basically extrapolating from a question that was already posted and answered in this forum that I modified but couldn't print to the command line. It is similar to a problem from my java lesson at college in which we were suppose to use the enhanced for loop on a three dimensional array. I get an error message that is "illegal start of expression" and "not a statement". I almost got it to compile but I'm missing something. I need some help. Here is the code:

public class ThreeDimensionalArray {

public static void main(String[] args) {
int[][][] array = new int[4][5][6];//initializing array
int sum = 0;//define sum
for (int[][] i : array)//start of enhanced for loop
{
for (int[] j : i)
for (int k : j)
sum += k;

System.out.println("Output is " + sum);//output sum
}//end enhanced for loop
}//end method main

}//end ThreeDimensionalArray

Answer

The println has to be after all loop.

public class ThreeDimensionalArray
{

public static void main(String[] args)
{
int[][][] array = new int[4][5][6];//initializing array
int sum=0;//define sum
for(int[][] i: array)//start of enhanced for loop
{
for(int[] j: i)

for(int k:j) 
sum +=[k];



}//end enhanced for loop
  System.out.println("Output is",sum);//output sum
}//end method main

//end ThreeDimensionalArray
}
Comments