2017-04-02 207 views
1

這是我的第一個問題,所以我可能聽起來很愚蠢,所以請不要介意! 我工作的一個概念,它是變參,我想出了一個程序如下:如何使用var args方法在java中添加int和int []?

package Method; 
public class VariableArguments { 
public static void main(String[] args) { 
    m1(); 
    m1(10); 
    m1(10,20); 
    m1(10,20,30,40); 
    m1(10,20,30,40,50); 
} 
public static void m1(int... x) 
{ 
    int total = 0; 
    for(int i:x) 
    { 
     total = total + x; 
    } 
    System.out.println("Sum is: "+total); 
} 
} 

當我運行這個程序,我得到的是─

Error:(15, 27) java: bad operand types for binary operator '+'

first type: int second type: int[]

錯誤在第15行中,它說「運算符'+'不能應用於int,int []」

那麼有人可以給我這個問題的解決方案嗎? 謝謝!

+2

應該是'total = total + i;'您正在迭代'x'數組。 – Justas

+0

非常感謝Justas! –

回答

1

您需要將total添加到i(每個元素),而不是var args。陣列(即,x),因此改變它的代碼爲:當執行此

total = total + i; 
+0

它現在正在工作..非常感謝你javaguy :) –

0

total = total + x; 

x是數組。您不能在陣列上使用+運算符,因此也會出現錯誤。 既然你迭代數組x過來,我感覺你想這樣的:

total = total + i; 
1

這個錯誤是因爲你正在嘗試做的數學運算與完全不兼容的數據類型......你事實上是在試圖增加與整數

陣列你的意思是肯定

total = total + i; 

因爲兩者的整數是相同的類型(INT)

做這個

total = total + x; 

要添加的int整數數組...

1

避免愚蠢的錯誤,你需要學習的的for-each方法:

for(int i : x) // this means for every integer value *i* in array *x* 
{ 
     total = total + i ;// this line add the i to total , 
    //total = total + x ;//here array is bad operand for '+' operator . 
} 

通過上面的snnipet改變你的代碼,或者你也可以使用簡單的for循環。

相關問題