循环语句可以将一段代码执行多次,Java里主要分为while循环语句,do … while循环语句和for循环语句。
1.while循环语句
对于while循环语句,如果条件为真则执行循环体内的语句,直到条件不成立,while循环结束。极其需要注意的是在循环体内对循环条件修改。
public class Demo {
public static void main(String[] args){
int x = 10;
while(x > 0){
System.out.println("x:"+x);
x--;
}
}
}
结果
x:10
x:9
x:8
x:7
x:6
x:5
x:4
x:3
x:2
x:1
2.do … while循环语句
do … while语句与while语句的差别不大,do … while语句会无条件执行一次,后面是否执行看判断条件语句。下面的例子很好地说明了这个问题,相同的条件,相同的初始值,do …while较while会首先无条件执行一次。
public class Demo {
public static void main(String[] args){
int x = 10;
int y = 10;
/*while */
do{
System.out.println("while x:"+x);
x--;
}while(x > 10);
/*do ... while */
while(y > 10){
System.out.println("do while y:"+y);
y--;
}
}
}
结果
while x:10
3.for循环语句
for循环是最常用的循环,用于循环次数已知的情况下。示例:求100以内对1~100进行求和。
public class Demo {
public static void main(String[] args){
int sum = 0;
for(int i=1; i<=100; i++){ //先i初始化,判断条件,执行循环,i自增,判断条件...
sum+=i;
}
System.out.println("sum:"+sum);
}
}
结果
sum:5050
4.循环嵌套
一个循环语句的循环体中可以再定义一个循环语句,while,do … while, for之间可以相互嵌套。
public class Demo {
public static void main(String[] args){
for(int i=1; i<=10; i++){ //外层循环
for(int j=1; j<=10; j++){ //内层循环
if(i == j){
System.out.print("+ "); //后面我加了空格看起来更方
}else{
System.out.print("- ");
}
}
System.out.print("\n"); //每一行敲完换行
}
}
}
结果
+ - - - - - - - - -
- + - - - - - - - -
- - + - - - - - - -
- - - + - - - - - -
- - - - + - - - - -
- - - - - + - - - -
- - - - - - + - - -
- - - - - - - + - -
- - - - - - - - + -
- - - - - - - - - +
5.跳转语句(break、continue)
- break语句
在switch语句和循环语句中都可以见到break的身影。在switch语句中,目的是终止某个case并跳出switch结构;在循环语句中,作用是跳出循环,结束循环。
public class Demo {
public static void main(String[] args){
int x = 10;
while(x > 0){
System.out.println("x:"+x);
if(x == 6){ //到6的时候结束循环
break;
}
x--;
}
}
}
结果
x:10
x:9
x:8
x:7
x:6
备注:当break遇到循环嵌套:当break出现在内层循环时,结束的是内层循环。如果想要结束外层循环时,需要对外层循环添加标记,结束外层循环格式为:break 标记名称。
public class Demo {
public static void main(String[] args){
mark : for(int i=1; i<=10; i++){ //外层循环
for(int j=1; j<=10; j++){ //内层循环
if(i == j){
System.out.print("+ "); //后面我加了空格看起来更方
}else{
System.out.print("- ");
}
}
System.out.print("\n"); //每一行敲完换行
if(i == 5){
break mark; //直接结束外层循环
}
}
}
}
结果
+ - - - - - - - - -
- + - - - - - - - -
- - + - - - - - - -
- - - + - - - - - -
- - - - + - - - - -
- continue语句
continue语句用来跳过本次循环但是下次循环会继续执行。例子:对100以内的偶数进行求和。
public class Demo {
public static void main(String[] args){
int sum = 0;
for(int i=1; i<=100; i++){
if(i % 2 == 0){ //为偶数跳出此次循环,但是下次循环接着执行
continue;
}
sum+=i;
}
System.out.println("sum:"+sum);
}
}
结果
sum:2500
备注:同break类似,当continue出现在内层循环时,跳过的是内层本次循环。如果想要跳过外层本次循环时,需要对外层循环添加标记,跳过外层本次循环格式为:continue 标记名称。