这是我的第一个问题,所以我可能听起来很蠢,所以请不要介意!我正在研究一个概念,即var args,我想出了一个程序如下:
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);
}
}当我运行这个程序的时候,我收到一个错误,就是-
错误:(15,27) java:二进制运算符的坏操作数类型'+‘第一个类型: int第二类型: int[]
在第15行中,它说“运算符'+‘不能应用于int,int[]”
有人能给我解决这个问题的办法吗?谢谢!!
发布于 2017-04-02 11:27:55
您需要将total添加到i (每个元素),而不是添加到var args。数组(即x),因此将代码更改为:
total = total + i;发布于 2017-04-02 11:29:42
错误是因为您试图使用完全不兼容的数据类型执行数学操作..。实际上,您正在尝试添加一个整数,其中包含一个ints数组。
你是说肯定
total = total + i; 因为两者都是相同的类型(Int)
通过这样做
total = total + x;您要将int添加到int数组中.
发布于 2017-04-02 11:34:48
避免愚蠢的错误,您需要为每个方法学习:
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来更改您的代码,或者您也可以使用simple for循环。
https://stackoverflow.com/questions/43167754
复制相似问题