我想将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;
}
答案 0 :(得分:1)
尝试分配x
和y
的值,如下所示:
int x = points.length;
int y = points[].length;
deltSum = new int[y];
了解如果Random值超出point[][]
数组的索引,那么肯定会给你运行时异常。
答案 1 :(得分:0)
如果您想要随机值,请在数组长度范围内使用Random Class
,以获得x
和y
的不同和随机值,并避免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