Java循环结构与判断结构

来源:互联网 发布:法国蜗牛知乎 编辑:程序博客网 时间:2024/05/16 09:51

1、三元运算符

(条件表达式)?表达式1:表达式2;

2、判断结构

  1. if else 可判断区间与布尔型。
  2. switch
    switch(表达式)

    case 取值1;
    执行语句;
    break;
    default;
    执行语句;
    break

    只接受byte、short、int、char类型。

3、循环结构

  • while循环
while(条件表达式)    {      执行语句;    }
  • do-while循环
do    {      执行语句;    }while(条件表达式);
  • for循环
    for(初始化表达式;循环条件表达式;循环后的操作表达式)    {        执行语句;    }

若定义循环增量,用for更合适。

4、break-continue结构

    break:应用于选择结构与循环结构。    continue:用于循环结构。

例1:使用嵌套循环输出下图

***************
class ForForTest1{    public static void main(String[] args)    {        int z=5;        for(int x=0;x<5;x++)        {            for(int y=0;y<z;y++)            {System.out.print("*");            }            System.out.println();            z--;        }    }}

例2:输出九九乘法表

class ForForTest2{    public static void main(String[] args)    {        for(int x=1;x<=9;x++)        {            for(int y=1;y<=x;y++)            {System.out.print(y+"*"+x+"="+y*x+"\t");            }            System.out.println();        }    }}

例3:输出下图

         *        * *       * * *      * * * *     * * * * *
class ForForTest3{    public static void main(String[] args)    {        for(int x=0;x<5;x++)        {            for(int y=x+1;y<5;y++)            {System.out.print(" ");            }            for(int t=0;t<=x;t++)            {System.out.print("*");            }            System.out.println();        }    }}
0 0
原创粉丝点击