for循环
for循环的用法是:
for (初始条件; 循环检测条件; 循环后更新计数器) {
// 执行语句
}
要对一个整型数组的所有元素求和,可以用for循环实现:
// for
public class Main {
public static void main(String[] args) {
int[] ns = { 1, 4, 9, 16, 25 };
int sum = 0;
for (int i=0; i<ns.length; i++) {
System.out.println("i = " + i + ", ns[i] = " + ns[i]);
sum = sum + ns[i];
}
System.out.println("sum = " + sum);
}}
for each循环
更简单地遍历数组:
// for each
public class Main {
public static void main(String[] args) {
int[] ns = { 1, 4, 9, 16, 25 };
for (int n : ns) {
System.out.println(n);
}
}}
标签:Main,int,循环,static,foreach,ns,public
From: https://www.cnblogs.com/lxy0827/p/18666988