2015-10-24 55 views
-1

我想總結一個二維數組到這個:Java二維數組求和(所有的總和)

我想要的方法來二維數組求和。但是,如果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

你會得到什麼例外? ArrayIndexOutOfBound? – SMA

+1

@SMA我運行了代碼,它是一個ArrayIndexOutOfBound。 – Ainvox

+0

@Ainvox這意味着OP需要爲x和y設置適當的值。 – SMA

回答

1

嘗試分配的xy如下值:

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

明白,如果隨機值超出point[][]數組的索引,那麼它必將給你運行時異常。

+1

如果我正確地理解了這個問題,這不能解決問題。 OP表示這些值是隨機的,因此它們不能設置爲一個常數值。 – Ainvox

+0

是的,但是如果這些「隨機」值超出了數組的大小,那麼整個問題就沒有多大意義。 – h22

+0

@h22我們可以給出這些「隨機」值的範圍,以便它們不會超出數組的大小。 –

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