break:终止,中断循环
public class test{
public static void main(String[] args){
for(int x = 0;x<=5;x++){
if(x ==3){
System.out.println(x);
break;/当条件满足时,终端程序
}
}
}
}
/*
Desktop\test>java test
3
*/
public class test{
public static void main(String[] args){
for(int x = 0;x<=5;x++){
if(x ==3){
break;//当条件满足时,终端程序
}
System.out.println(x);
}
}
}
/*
0
1
2
*/
重点:
public class test{
public static void main(String[] args){
int x = 1; //在循环外声明变量
int y =1;
for(;x<=5;x++){
for(;y<=5;y++){
if(y ==3){ //循环时取到的变量是累积赋值过后的变量,也就是第2轮循环x,y分别为:x-->2,y-->3,只剩外层循环在继续,内层循环一直中断
break;//当条件满足时,终端程序
}
System.out.println("OK");
}
}
}
}
/*
Desktop\test>java test
OK
OK
*/
public class test{
public static void main(String[] args){
for(int x =1;x<=5;x++){//在循环内声明变量
for(int y = 1;y<=5;y++){ //每次循环开始都将变量初始为1
if(y ==3){
break;//当条件满足时,终端程序
}
System.out.println("OK");
}
}
}
}
/*
Desktop\test>java test
OK
OK
OK
OK
OK
OK
OK
OK
OK
OK
*/
break中断外层循环:
public class test{
public static void main(String[] args){
ok:for(int i = 1;i<=5;i++){ //循环标记
ko:for(int j=1;j<=5;j++){
if(j==3){
break ok;//中断标记的循环
}
System.out.println("i:"+i+"j:"+j);
}
}
}
}
/*
Desktop\test>java test
i:1j:1
i:1j:2
*/
continue:
public class test{
public static void main(String[] args){
for(int i = 1; i <=5; i++){
if(i==3){
continue;//中断本次循环,继续下一次循环
}
System.out.println(i);
}
}
}
/*
Desktop\test>java test
1
2
4
5
*/
while循环语法:
初始值放在外面;
while(只允许写一个终点判断条件){
变化量;
}
public class test{
public static void main(String[] args){
int i =1;
while(i<=5){
System.out.println(i);
i++;
}
}
}
do{} while()语法:
do{
变化量;
}while(条件);
public class test{
public static void main(String[] args){
int i =1;
do{
System.out.println(i);
i++;
}while(i<=5);
}
}
public class test{
public static void main(String[] args){
int i =10;
do{
System.out.println(i);
i++;
}while(i<=5);
}
}
do while与while区别:
do while:先执行后判断,至少执行一次
while:先判断,再执行