Java 2D数组总和(全部添加)

时间:2015-10-24 10:36:57

标签: java arrays

我想将2D数组求和:

我希望该方法对2D数组求和。但是,如果x大于y,则程序会获得异常。我试着调试它,但我不知道如何顺利​​修复它。如果x大于y,我应该创建另一种方法吗? Points是包含所有值的数组。

 int x = //Random value
 int y = //Random value
 deltSum = new int[y];

 int output = 0;
 for (int t = 0; t < x; t++) {
    for (int i = 0; i < y; i++) {
        output += points[t][i]; //Add all values in the first section of the array.
    }
    deltSum[t] = output;
    System.out.println(output);
    output = 0;
 }

2 个答案:

答案 0 :(得分:1)

尝试分配xy的值,如下所示:

int x = points.length;
int y = points[].length;
deltSum = new int[y];

了解如果Random值超出point[][]数组的索引,那么肯定会给你运行时异常。

答案 1 :(得分:0)

如果您想要随机值,请在数组长度范围内使用Random Class,以获得xy的不同和随机值,并避免ArrayIndexOutOfBound异常。

import java.util.Random; //to use Random Class...

...

Random randomGenerator = new Random(); //making instance of Random

//these statements will assign a value to x & y that is random 
//and smaller than the maximum length which is specified.
int x = randomGenerator.nextInt(points.length); //Will assign random value to x less then points.length
int y = randomGenerator.nextInt(points[0].length); ////Will assign random value to x less then points[].length