问题描述
我无法运行此程序。它应该将一个数组作为输入并输出一个具有输入数组累加和的新数组。我为此使用了一个函数(底部)。
例如:
Input: 1 2 3 4
Output: 1 3 6 10
这是我的程序:
import java.util.Scanner;
public class Accumulate {
public static void main(String[] args) {
int n,sum = 0;
Scanner s = new Scanner(system.in);
System.out.print("Enter the size of the array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
}
System.out.println(Arrays.toString(accSum(a)));
s.close();
}
public static int[] accSum(int[] in) {
int[] out = new int[in.length];
int total = 0;
for (int i = 0; i < in.length; i++) {
total += in[i];
out[i] = total;
}
return out;
}
}
解决方法
使用 Arrays.toString()
打印数组。
您不能直接调用 System.out.println(accSum(a));
,因为它会打印数组的内存地址而不是内容。用 Arrays.toString(accSum(a))
包装调用,它将打印预期的输出。
PS:您帖子中的代码无法编译:
-
scanner.close();
应该是s.close();
-
accSum()
应该是静态的。
附录: 所以你的完整代码变成了这样:
public static void main(String[] args) {
int n,sum = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter the size of the array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
}
System.out.println(Arrays.toString(accSum(a)));
s.close();
}
public static int[] accSum(int[] in) {
int[] out = new int[in.length];
int total = 0;
for (int i = 0; i < in.length; i++) {
total += in[i];
out[i] = total;
}
return out;
}
,
您可以使用 Arrays.stream(int[],int,int)
方法来获取前面数组元素的总和:
public static void main(String[] args) {
int[] arr1 = {1,2,3,4};
int[] arr2 = accSum(arr1);
System.out.println(Arrays.toString(arr2));
// [1,6,10]
}
public static int[] accSum(int[] arr) {
return IntStream
// iterate over the indices of the array
.range(0,arr.length)
// sum of the current element and all previous elements
.map(i -> arr[i] + Arrays.stream(arr,i).sum())
// return an array
.toArray();
}