我的方法将求和一个数组的元素(或组件或任何您称呼它们的对象)。但是,以下代码的 a.length()部分无效。
My method will sum the elements (or components or whatever you would call them) of an array. The a.length() part of the following code doesn't work though.
public double ArraySum(double[] a) { double sum = 0; double Element; for(Element = 0; Element < a.length(); Element++) { sum = sum + a[Element]; } }有人可以告诉我为什么.length方法突然不起作用
Could anyone tell me why the .length method suddenly doesn't work?
推荐答案因为数组具有 length 字段,而不是长度方法。而且,按照惯例,Java变量名称以小写字母开头(方法名称也是如此; ArraySum 应该可能是 getArraySum 或 sumArray )。不需要使用 double 作为循环计数器,您可以使用 + = 。更改
Because arrays have a length field, not a length method. And, by convention, Java variable names start with a lower case letter (and so do method names; ArraySum should probably be getArraySum or sumArray). There's no need to use a double as your loop counter and you could use +=. Change
double Element; for(Element = 0; Element < a.length(); Element++) { sum = sum + a[Element]; }类似
for(int element = 0; element < a.length; element++) { sum += a[element]; }或,您可以使用增强的 for-each 循环,例如
or you could use an enhanced for-each loop like
for(double element : a) { //<-- for each element in the array. sum += element; //<-- add the element to the sum. }更多推荐
数组求和法
发布评论