我正在为暑期 Java 类(class)做一个简单的作业,只是希望你们能看看我的代码,看看我的做法是否是最好的方法。目的是创建一个至少包含 25 个元素的简单 int
数组,并使用循环遍历它并将所有元素相加。我遇到了一些问题,但看起来我可以正常工作了。在我解决之后,我做了一些研究并看到了一些类似的东西,人们正在使用 For Each 循环(增强循环)。那会是更好的选择吗?我对使用它而不是常规 for 循环的最佳方式感到困惑。
无论如何,任何帮助我成为更好的程序员的评论或批评!
public class Traversals {
public static void main(String[] args) {
int absenceTotal = 0;
// initialize array with 30 days of absences.
int absencesArr[] = { 1, 3, 0, 9, 8, 23, 1,
11, 23, 5, 6, 7, 10, 1, 5,
14, 2, 4, 0, 0, 1, 3, 2, 1,
1, 0, 0, 1, 3, 7, 2 };
for (int i = 0; i < absencesArr.length; i++) {
absencesArr[i] += absenceTotal;
absenceTotal = absencesArr[i];
}
System.out.println("There were " + absenceTotal + " absences that day.");
}
}
最佳答案
不要修改数组。我更喜欢 for-each
loop .你应该考虑到可能有很多学生,所以我可能会使用 long
作为 sum
。并格式化输出。把它放在一起变成类似的东西
long sum = 0;
for(int i : absencesArr) {
sum += i;
}
// System.out.println("There were " + sum + " absences that day.");
System.out.printf("There were %d absences that day.%n", sum);
关于java - 数组中元素的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31196967/