簡體   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