Reputation: 35
I want to create a program with the following objectives.
1.1. Declare a two dimensional (10 x2, ie. 10 rows and 2 columns) integer array and populate it with random integers.
1.2. Create an object of the ArraySum class.
1.3. Pass the array in Step 1.1 by calling Summation (int [][] myArray)
1.4. Print the return value of Summation (int[][] myArray)
2.1. Calculate the summation of all the elements in myArray.
2.2. Return the summation.
So far I have this code.
public class ArraySum {
public int Summation(int[][] myArray) {
int sum = 0;
int num = 0;
for( int num : array) {
sum = sum+num;
}
return sum;
}
public static void main (String[] args) {
Summation summation = new Summation();
int sum = 0;
int[][] myArray = new int[][] {
{1, 2},
{3, 4},
{5, 6},
{7, 8},
{9, 10},
{11, 12},
{13, 14},
{15, 16},
{17, 18},
{19, 20}
};
Sum = Summation(int[][] myArray);
return Sum;
}
}
I'm getting two errors resulting from the myArray class missing, apparently. Any help would be appreciated.
Upvotes: 2
Views: 60
Reputation: 10254
public class HelloDate {
public static int Summation(int[][] myArray) {
int sum = 0;
for (int i = 0; i < myArray.length; i++) {
for (int j = 0; j < myArray[0].length; j++) {
sum += myArray[i][j];
}
}
return sum;
}
public static void main(String[] args) {
int[][] myArray = new int[][] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 }, { 9, 10 }, { 11, 12 }, { 13, 14 },
{ 15, 16 }, { 17, 18 }, { 19, 20 } };
int sum = HelloDate.Summation(myArray);
System.out.println(sum);
}
}
Please refer this code:
1、public static void main(String[] args)
you can't return any value from this method.
2· for 2D array, you need use for loop to access each element.
3、Sum = Summation(int[][] myArray);
is wrong, when you call a method, you just need pass a paramter.
Upvotes: 1