Emmanuel Harrison Emmanuel Harrison - 7 months ago 10
Java Question

Adding values on 2d array java

I have created a program that lets the user input the number of rows and columns they want in a 2d array and then it fills the array with all even numbers starting from 0.

I have to add all the numbers in the array to get a total sum and I have no idea how to do that. The rest of my program is complete I'm just having trouble with the sum.

Here is my code:

import java.util.*;

public class ArrayOver {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("How many rows? ");
int x = scan.nextInt();
System.out.println("How many columns? ");
int y = scan.nextInt();

int[][] nums = new int[x][y];
fillArray(nums);
displayArray(nums);
System.out.println();
}

public static void fillArray(int nums[][]) {
int count = 0;
for (int row = 0; row < nums.length; row++) {
for (int col = 0; col < nums[0].length ; col++) {
nums[row][col] = count;
count++;
count++;
}
}
}

public static void displayArray(int nums[][]){
for (int row = 0; row < nums.length; row++) {
System.out.println(Arrays.toString(nums[row]));
}
}
}

Answer

Try this:

public static void countArray(int[][] nums)
{
  int total=0;

  for (int row=0;row<nums.length;row++)
    for (int col=0;col<nums[0].length;col++)
      total += nums[row][col];

  System.out.println(total);
}

This should go through all the numbers in the array and add their values to total.

Comments