繁体   English   中英

Java 2D 数组总和(所有的相加)

[英]Java 2D array sum (addition of all)

我想将一个二维数组与此相加:

我想要对二维数组求和的方法。 但是,如果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;
 }

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

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

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

如果你想要随机值,那么在数组长度范围内使用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

暂无
暂无

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

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