[英]Take array as input from user and output accumulative sum as new array
I can't get this program to work.我无法让这个程序工作。 It's supposed to take an array as input and output a new array with the accumulative sum of the input array.它应该将一个数组作为输入,output 一个新数组,输入数组的累积和。 I used a function for this (bottom part).我为此使用了 function(底部)。
For example:例如:
Input: 1 2 3 4
Output: 1 3 6 10
Here's my program:这是我的程序:
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;
}
}
Use Arrays.toString()
to print an array.使用Arrays.toString()
打印一个数组。
You can't call System.out.println(accSum(a));
你不能调用System.out.println(accSum(a));
directly as that will print the memory address of the array and not the contents.直接因为这将打印数组的 memory 地址而不是内容。 Wrap the call with Arrays.toString(accSum(a))
and it will print the expected output.用Arrays.toString(accSum(a))
包装调用,它将打印预期的 output。
PS: The code in your post doesn't compile: PS:您帖子中的代码无法编译:
scanner.close();
should be s.close();
应该是s.close();
accSum()
should be static. accSum()
应该是 static。Addendum: So your full code became this:附录:所以你的完整代码变成了这样:
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;
}
You can use Arrays.stream(int[],int,int)
method to get the sum of the previous array elements:您可以使用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, 3, 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, 0, i).sum())
// return an array
.toArray();
}
See also: Modifying a 2D array另请参阅:修改二维数组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.