Noo*_*ick 6 java arrays foreach for-loop traversal
我正在为一个夏季java课程做一个简单的任务,只是希望你们可以看看我的代码,看看我做的方式是否是最好的方法.目的是创建一个int包含至少25个元素的简单数组,并使用循环遍历它并添加所有元素.我遇到了一些问题,但看起来我已经开始工作了.在我解决之后,我做了一些研究,看到了一些类似的东西,人们使用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.");
}
}
Run Code Online (Sandbox Code Playgroud)
不要修改数组.我更喜欢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);
Run Code Online (Sandbox Code Playgroud)
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.");
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10497 次 |
| 最近记录: |