美文网首页
Java:if和for

Java:if和for

作者: iOS_修心 | 来源:发表于2023-05-11 22:59 被阅读0次

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

  • continue 用在循环中,基于条件控制,跳过某次循环体内容的执行,继续下一次的执行

  • break 用在循环中,基于条件控制,终止循环体内容的执行,也就是说结束当前的整个循环

8.增强 for 循环

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

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

相关文章

网友评论

      本文标题:Java:if和for

      本文链接:https://www.haomeiwen.com/subject/jwrdsdtx.html