Java:if和for

2023-05-11  本文已影响0人  iOS_修心

1.if语句

   int x = 30;
   if( x == 10 ){
      System.out.print("Value of X is 10");
   }else if( x == 20 ){
      System.out.print("Value of X is 20");
   }else if( x == 30 ){
      System.out.print("Value of X is 30");
   }else{
      System.out.print("这是 else 语句");
   }

2.switch语句


如果case控制的语句体后面不写break,将出现穿透现象,在不判断下一个case值的情况下,向下运行,直到遇到break,或者整个switch语句结束

   static  void test2(){
       int light =1;
       switch (light) {
           case 1:
               System.out.println("红灯停");
               break;
           case 2:
               System.out.println("绿灯行");
               break;
           case 3:
               System.out.println("黄灯亮了等一等");
               break;
           default:
               System.out.println("交通信号灯故障,请在保证安全的情况下通行");
               break;
       }

3.for循环

     for(int i=1; i<=5; i+=1) {
         System.out.println("HelloWorld");
     }

4.while循环

        int i = 1;
        while (i<=5) {
            System.out.println("HelloWorld");
            i++;
        }

5.do…while循环

      int i = 1;
      do {
          System.out.println("HelloWorld");
          i++;
      } while (i<=5);

6.三种循环语句的区别:

for循环和while循环先判断条件是否成立,然后决定是否执行循环体(先判断后执行)

do...while循环先执行一次循环体,然后判断条件是否成立,是否继续执行循环体(先执行后判断)

7. continue 和 break

8.增强 for 循环

for(声明语句 : 表达式)
{
//代码句子
}

      int [] numbers = {10, 20, 30, 40, 50};
 
      for(int x : numbers ){
         System.out.print( x );
         System.out.print(",");
      }
上一篇 下一篇

猜你喜欢

热点阅读