JAVA基础知识学习笔记(一)--JAVA循环结构

JAVA的循环结构

Java循环结构主要有三种:

  • while循环
  • do…while循环
  • for循环

while循环

语法结构:


while( 布尔表达式 ) {
  //循环内容
}

实例:


public class Test {
   public static void main(String args[]) {
      int x = 10;
      while( x < 20 ) {
         System.out.print("value of x : " + x );
         x++;
         System.out.print("\n");
      }
   }
}

do…while循环

即使不满足条件,也至少执行一次循环。
语法结构

do {
       //代码语句
}while(布尔表达式);

实例


public class Test {
   public static void main(String args[]){
      int x = 10;
 
      do{
         System.out.print("value of x : " + x );
         x++;
         System.out.print("\n");
      }while( x < 20 );
   }
}

for循环

for循环使循环结构变得更加简单。
for循环执行的次数在之前前就已经确定的。
语法结构:


for(初始化; 布尔表达式; 更新) {
    //代码语句
}

实例:


public class Test {
   public static void main(String args[]) {
 
      for(int x = 10; x < 20; x = x+1) {
         System.out.print("value of x : " + x );
         System.out.print("\n");
      }
   }
}

小知识点:在java中,++x和x++是不一样的
int a =3; int b = (a++)+(++a)+2;
答案是a=5,b=3+5+2=10

break 关键字

break的主要用在循环语句或者是switch语句中,用来跳出整个语句块。
break跳出最里层的循环,并且继续执行该循环下面的语句。
实例:


public class Test {
   public static void main(String args[]) {
      int [] numbers = {10, 20, 30, 40, 50};
 
      for(int x : numbers ) {
         // x 等于 30 时跳出循环
         if( x == 30 ) {
            break;
         }
         System.out.print( x );
         System.out.print("\n");
      }
   }
}

continue 关键字

continue 的作用是让程序立即跳转到下一次循环的迭代。
有点类似于操作循环“回溯”。
实例:


public class Test {
   public static void main(String args[]) {
      int [] numbers = {10, 20, 30, 40, 50};
 
      for(int x : numbers ) {
         if( x == 30 ) {
        continue;
         }
         System.out.print( x );
         System.out.print("\n");
      }
   }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值