2016-05-29 20 views
-1

我在for循環之前聲明瞭數組,現在我想將for循環的結果連接到數組中。以下不起作用,並給我錯誤爲「錯誤:無法找到符號」。在java中連接數組中循環的結果

我的代碼是

for(int j=i; j<=arr.length-1; j++){    

    // checking for condition 
    if (i<j) 
    { 
     int temp = arr[i]+arr[j]; 
     if (temp%sum==0) { 
     System.out.println("Pair with given sum " + 
          sum + " is (" +temp+")"); 
      result[] += temp; 
     } 
    } 
+0

對不起,我忘了在福爾循環包括,談到之前的if語句 – aditya

+3

'結果[] + = temp'顯然是不正確。這個數組最初是在哪裏申報的? – Makoto

+0

聲明結果[]數組並將temp插入數組的某個索引。 例如result [i] = temp。如果您不知道結果數組的最終大小,您可以使用arraylist。 – Gihanmu

回答

2

你的錯誤是在這裏

result[] += temp; 

您需要提供一個索引你的數組,其中它可以存儲值

嘗試是這樣的

result[i] += temp; 

還要注意這將創建一個具有不同temp值的數組。

加在你for循環,你正在做j=i,然後檢查

if(i<j)

所以,你的循環將在1次迭代運行,因爲第一次的條件將是錯誤的。

如果您不必打印值temp並且只有值的數量,那麼您根本不需要數組。

您可以簡單地創建一個變量

int count=0;

,然後改變你的for循環這樣的事情

if (temp%sum==0) { 
     System.out.println("Pair with given sum " + 
          sum + " is (" +temp+")"); 
      count++; 
     } 

然後打印計數。

如果使用陣列是強制性的,你可以打印數組的長度一樣

result.length

希望這有助於:)

+0

嗨@aradhana謝謝你的幫助,但事情是我需要添加一個數組中的所有臨時值,以便我可以打印出該數組的數量 – aditya

+0

所以,你的意思是你需要存儲(而不是添加)臨時值在一個數組中,然後至少要打印存儲在數組中的項目數量? – Aradhna

+0

是的,我想存儲在溫度值陣列和打印項目數 – aditya

0

你的代碼是這樣的..何況結果指數環和使用前申報。 click here查看錯誤發生的原因。

你能提供int i的價值,這樣我們可以幫你循環。

int result = new int[100] //give value according to your program. 
for(int j=i; j<=arr.length-1; j++){    
// checking for condition 
if (i<j) 
{ 
    int temp = arr[i]+arr[j]; 
    if (temp%sum==0) { 
    System.out.println("Pair with given sum " + 
         sum + " is (" +temp+")"); 
     result[j] += temp; 
    } 
} ` 
+0

這仍然給我一個錯誤,因爲「錯誤:找不到符號 int result = new result [100];」 – aditya

+0

我編輯了我的答案,再試一次。 – yash

+0

抱歉,我只需要循環中存儲的元素的索引....你寫的代碼只會增加索引。 – aditya

0

的陣列不因爲你可能think.When您創建工作例如 如果你想:數組這樣

int x[10] = new int[10]; 

,你可以像這樣訪問數組中的元素第一個元素x[0]第二個x[1](你的statrt從0到數組長度-1計數)。所以你在這裏做:

result[] += temp; 

不作sense.You高度重視和始終指定你想訪問(你可能要像 result[index] += temp;)的元素的索引。

我希望我能幫上忙。

+0

循環將不會工作的第一次迭代,這就是我想要的 – aditya

+0

哦,你希望它不能正常工作,那麼我會刪除那部分。 – theVoid

0

你的錯誤是在行

result[] += temp; 

你需要提及你想連接的結果數組索引。 對於如

//your code goes here 
..... 
for (int k = index_of_resultArray_to concatenate; k < result.length; k++) { 
    result[k] += temp; 
}