2016-02-22 31 views
-1

我正在嘗試用點500-700創建一個數組。數組中的總空間是200.我在做什麼錯了?添加到數組Java

int[] anArray = new int[200]; 

for (int j = 0; j <200; j++){ 
    for (int h = 500; h <700; h++){ 
     anArray[j] = h+1; 
    } 
} 
+0

錯誤信息是什麼? –

+0

你有錯誤嗎? –

+0

當我打印anArray [2]時,它會打印700 – LifeofBob

回答

6

您當前密碼的效果設置你要找的anArray到700的所有元素的東西要簡單得多:

for (int j = 0; j <200; j++) 
    anArray[j] = 500 + j; 
+0

謝謝!這工作 – LifeofBob

+0

不客氣!我希望你明白爲什麼你的嵌套for循環沒有做到這一點? – Kenney

+0

我寧願做'anArray.length'然後聲明200爲int。 –

0

你並不需要一個內部循環!

只需將500添加到j。

所以在內部循環它應該是anArray [j] = j + 500;

0

您正在使用嵌套循環,因此您的數組空間不足。

只要做到以下

for (int j=0;j<200;j++) 
{ 
    anArray[j] = j+500; 
} 

注:我以爲你不希望在陣列中700。如果你這樣做,只是一個

0

上升的空間你迭代500的200倍到700,這是不是你期待什麼?

做,而不是:

for (int j = 0; j < 200; j++) { 
      System.out.println(j); 
      anArray[j] = 500 + j; 
     } 
0

好,實際上你在數組的每個單元格中寫入了[500..700]的值。 該代碼做exacly你想要什麼:

int size = 200; 
int[] anArray = new int[size]; 
offset = 500; 
for (int j = 0; j <size ; j++){ 
    anArray[j] = offset + i; 
} 
0

如果您通過700加500的整數,你可以嘗試以下的能力之後是:

int[] anArray = new int[200]; 

for (int j = 0; j <anArray.length; j++) 
{ 
    anArray[j] = 500 + j; 
} 
0

試試這個:

int[] anArray = new int[200]; 
    int plusWith=500; 
     for (int j = 0; j <200; j++){ 
        anArray[j] = j+plusWith; 
     } 
0

沒有解決您的算法的問題,但作爲替代解決方案:

int[] range = IntStream.rangeClosed(500, 700).toArray(); 

需要Java 8

0

這是它是如何工作的:

iteration 1 : 
value of j is 0 
then the inner loop will iterate from 500 to 700 and at the last 
the value of anArray[0] which is the first element will be set to 700. 

同樣會發生在其他的迭代,以及仍然您得到從600到一些數組元素700的不同值
因爲j被增加,範圍設置的值正在下降

這就是爲什麼你應該在這裏使用一個循環爲@Kenney explai斯內德。

我希望你明白。 :-)