我正在解决以下问题:
编写一个只有一个实例变量(整数数组)的对象类。您的构造函数应该将整数数组作为其唯一参数。编写所有访问器、修改器、toString 和 equals 方法。还要编写一个附加的 RECURSIVE 方法,该方法返回数组中所有元素的总和(您的方法应该有一个数组作为参数,并且在一般情况下应该在其返回中包含递归调用)。编写一个客户端类来测试您的所有方法,尤其是递归方法。
由于某种原因,我的 toString 方法有一个错误,并且我的递归方法也有一个错误,该方法应该返回数组的总和。我可能对其中一些代码还有很长的路要走,所以感谢您的帮助。
这是我到目前为止所拥有的...
客户端类别(用于测试方法)
package weeklylab9;
public class Client {
public static void main(String[] args) {
ObjectClass numArray = new ObjectClass; //trying to create new object so I can use toString method
numArray.toString(); //calling toString method?
}
}
对象类
package weeklylab9;
import java.util.Arrays;
import java.util.stream.*;
public class ObjectClass {
int[] numArray = {10,10,20,20,40};
public int[] getArray() { //this is my accessor method
return numArray;
}
public int[] setArray(int[] newa) { //this is my mutator method
this.numArray = newa;
return this.numArray;
}
public String toString() { //this is my toString method
Arrays.toString(int[], numArray);
}
public int recursionSum(int[] numArray) { //this should be a recursion method that returns sum of array elements
int sum = IntStream.of(numArray).sum();
System.out.println("The sum is : " + sum);
}
}
最佳答案
您的 toString() 方法应如下所示:
public String toString() {
return Arrays.toString(numArray);
}
您缺少 return 语句,并且对 Arrays.toString() 的调用有一个额外的错误参数。
用递归计算总和是毫无意义的,但这里有一个解决方案: https://stackoverflow.com/a/20253717/8883654
关于java - 返回数组总和的 toString 方法和递归方法中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47106631/