For循环
-
虽然所有循环结构都可以用while或者do…while表示,但Java提供了另一种语句——for循环,使一些循环结构变得更加简单。
-
for循环语句是支持迭代的一种通用结构,是最有效、最灵活的循环结构。
-
for循环执行的次数是在执行前就确定的。语法格式如下:
*简便操作:100.for====for(int i=1;i<=100;i++)*
- 练习一:计算0到100之间的奇数和偶数的和
package com.sun.struct;
public class ForDemo02 {
public static void main(String[] args) {
int a=0;
int b=0;
for(int i=0;i<=100;i++){
if(i%2==0){
a+=i;
}else{
b+=i;
}
}
System.out.println("偶数之和:"+a);
System.out.println("奇数数之和:"+b);
}
}
- 练习二:用while或for循环输出1-100之间能被5整除的数,并且每行输出3个
package com.sun.struct;
public class ForDemo03 {
public static void main(String[] args) {
for(int i=1;i<=1000;i++) {
if (i % 5 == 0) {
System.out.print(i + "\t");
}
if(i % (5 * 3) == 0) { //换行
System.out.println();
//System.out.println("\n");
}
}
//println 输出完会换行
//print 输出完不会换行
}
}
我自己做的:
package com.sun.struct;
public class ForDemo007 {
public static void main(String[] args) {
int j=0;
for(int i=1;i<=1000;i++){
if (i % 5 == 0) {
j++;//被5整除的个数
System.out.print(i + "\t");
if(j%3==0) {
System.out.println();
}
}
}
}
}