[英]Sum of elements in an array
我正在为一个夏季java课程做一个简单的任务,我只是希望你们能看看我的代码,看看我做的方式是否是最好的方法。 目的是创建一个包含至少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
循环 。 你应该考虑到可能会有很多学生,所以我可能会花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);
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++) {
// remove this
//absencesArr[i] += absenceTotal;
absenceTotal += absencesArr[i]; //add this
}
System.out.println("There were " + absenceTotal + " absences that day.");
}
}
除了其他很好的贡献,我喜欢for-each loop
,通常会在一行中完成。
for(int i : absencesArr) absenceTotal += i;
System.out.printf("There were %d absences that day.", absenceTotal);
但在某些情况下,当我想控制我的对象大小/长度/计数时,我将使用for loop
,如下例所示:
for (int i = 0; i < absencesArr.length; i++) absenceTotal += absencesArr[i];
System.out.printf("There were %d absences that day.", absenceTotal);
如果我需要在for loop
或for-each loop
有多行代码,那么我将它们全部放在大括号{ more than one line of code }
。
在Java 8中,您可以使用stream api:
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 };
absenceTotal = IntStream.of(array).sum();
System.out.println("There were " + absenceTotal + " absences that day.");
}
}
我知道最短的方式是:
int sum=Arrays.stream(absencesArr).sum();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.