2017-04-02 69 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循环。

相关问题