繁体   English   中英

在2D数组Java上添加值

[英]Adding values on 2d array java

我创建了一个程序,该程序允许用户在2d数组中输入所需的行数和列数,然后用从0开始的所有偶数填充数组。

我必须将数组中的所有数字相加以获得总和,而我不知道该怎么做。 我的程序的其余部分完成了,我只是遇到了麻烦。

这是我的代码:

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

如果要对数组的所有元素求和,只需执行以下操作:

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

尝试这个:

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);
}

这应该遍历数组中的所有数字并将它们的值相加。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM