【发布时间】:2021-02-26 11:24:38
【问题描述】:
我无法让这个程序运行。它应该将一个数组作为输入并输出一个新数组,其中输入数组的累积和。我为此使用了一个函数(底部)。
例如:
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;
}
}
【问题讨论】:
-
请说明该程序在何种情况下无法运行。你得到一个编译错误。如果没有,你会得到一个例外。尝试在 accSum 函数的入口处设置断点,以检查数组是否包含输入的数据。
-
示例:(数组大小)输入:5; (输入所有元素)输入:1 2 3 4 5。我得到一个 ArrayIndexOutOfBounds 异常,“Index 5 out of bounds for length 5”。
-
检查你的大括号如何匹配。特别是,查看 accSum 定义之前的大括号。确保你的缩进是正确的,否则你会感到困惑。此外,使用 4 个空格进行缩进是常规的(但不是必需的)。
标签: java arrays sum accumulate