循环语句
1、for循环
语法:
for(初始化 ; 条件表达式 ; 增量 ){
//执行代码
}
注:执行顺序,初始化–条件表达式判断为真–执行代码–增量–判断条件表达式为真–执行代码–增量–直至条件表达式为假,跳出循环,循环结束
例如:
//使用for将1到10累加将结果打印
public class ForTest{
public static void main(String[] args){
int sum=0;
for(int i=1 ; i<=10 ; i++){
sum+=i;
}
System.out.println("1到10累加和为:"+sum);
}
}
2、while语句
语法:
while(循环条件){
循环体
}
注:循环条件为true,执行循环体,否则循环结束
例如:
//使用while将1到10累加将结果打印
public class WhileTest{
public static void main(String[] args){
int sum=0;
int i=1;
while(i<=10 ){
sum+=i;
i++;
}
System.out.println("1到10累加和为:"+sum);
}
}
3、do while语句
do while和while类型,不过do while先执行一次,再去判断循环条件
语法:
do{
循环体
}while(循环条件);
注:do while循环的循环条件括号后面有 ;
例如:
//使用do while将1到10累加将结果打印
public class DoWhileTest{
public static void main(String[] args){
int sum=0;
int i=1;
do{
sum+=i;
i++;
}while(i<=10 );
System.out.println("1到10累加和为:"+sum);
}
}
4、循环嵌套
例如:
//往控制台上输出以下内容:
*
**
***
****
*****
******
*******
public class Test{
public static void main(String[] args){
//i行数
for(int i=0;i<7;i++){
//*号个数
for(int j=0;j<i+1;j++){
System.out.print("*");
}
//换行
System.out.println();
}
}
}
4、break和continue
注:break和continue一般都是结合循环使用(for/while/do-while)
break:终止整个循环
continue:终止本次循环,跳过这次循环循环继续
例如:
//break
for(int i=0;i<5;i++){
if(i==2){
break;
}
System.out.println("i = "+i);
}
输出结果:
i = 0
i = 1
//continue
for(int i=0;i<5;i++){
if(i==2){
continue;
}
System.out.println("i = "+i);
}
输出结果:
i = 0
i = 1
i = 3
i = 4
5、label标签
循环嵌套是可以使用label标签作用于指定循环,默认是最近的
例如:
f1:for(int i=0;i<3;i++){
f2:for(int j=0;j<5;j++){
if(j==3){
break f1;
}
System.out.println("j = "+j);
}
}
输出结果:
j = 0
j = 1
j = 2