当我们学习Java这门语言时,就要学习到Java中的for循环,很多初学者在学习for的循环时,不理解他的含义,今天我们就来看看,for的循环主要有三种,分别时for循环,while循环和do....while循环。
1,for循环
package com;
public class Elepse1 {
public static void main(String args[]) {
int sun=0;
for(int i=1;i<=10;i++) {
sun+=i;
}
System.out.println("sun="+sun);
}
}
运行结果 sun=55
首先要算出1+2+3....+10结果。所以我们该他一个值sun并且标明属性初始化。int sun=0;。for循环中但i=1,i<=10.i要加上1。所以sun=1,i=2时,i同样是<=10,所以此时sun=1+2=3。一值到i=10时,i还是满足i<=10.此时sun=1+2+3+4+5+6+7+8+9+10=55。而因为i++。所以i=11.不满足i<=10。所以跳出for循环。i只加到10。
2,while循环
package com;
public class Elepse2 {
public static void main(String[] args){
int i=1;
int sum=0;
while(i<=10){
sum+=i;
i++;
}
System.out.println(sum);
}
}
运行结果 sun=55
while循环是先判断i<=10。然后i=1再赋给sum.i再加上1。但i等于11时跳出循环。特点是先判断再执行。
3,do....while循环。
package com;
public class Elepse3 {
public static void main(String args[]) {
int i=1;
int sun=0;
do {
sun+=i;
i++;
}
while(i<=10);
System.out.println("sun="+sun);
}
}
运行结果 sun=55
do....while循环是先在do中执行,当i=11时跳出,然后再输出。特点是先执行在判断。