[英]Java 2D array sum (addition of all)
I want to sum a 2D array to this:我想将一个二维数组与此相加:
I want the method to sum a 2D array.我想要对二维数组求和的方法。 However, if
x
is greater than y
the program gets an exception.但是,如果
x
大于y
,程序会出现异常。 I tried to debug it, but I do not know how to fix it smoothly.我试图调试它,但我不知道如何顺利修复它。 Should I create another method if
x
is greater than y
?如果
x
大于y
我应该创建另一种方法吗? Points
is the array with all the values. 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;
}
Try to assign values of x
and y
as below:尝试分配
x
和y
值,如下所示:
int x = points.length;
int y = points[].length;
deltSum = new int[y];
Understand that if the Random values are out of the index of point[][]
array, then it will surely give you runtime exceptions.了解如果 Random 值超出
point[][]
数组的索引,那么它肯定会给你运行时异常。
If you want random values then use Random Class
within the range of length of the array to get different and random values of x
and y
and avoid ArrayIndexOutOfBound
exception.如果你想要随机值,那么在数组长度范围内使用
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.