Emmanuel Harrison Emmanuel Harrison - 1 year ago 92
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];

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;

public static void displayArray(int nums[][]){
for (int row = 0; row < nums.length; row++) {

Answer Source

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];


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download