分支语句

分支语句

分支语句(switch):有时也被称为“选择语句”、“开关语句”、“多重条件句”。

语法:

         switch(表达式)

         {

               case常量1:

              语句1

              [break;]

               case常量2:

              语句2

              [break;]

               …

               case常量n:

              语句n

               [break;]

              [default:]

            默认处理语句
       [break;]
      }

注意:

         1)switch(表达式)返回的值必须是1)byte型、2)char型、3)short型、4)int型。

         2)常量的值必须和表达式的值的类型相一致。

         3)常量的值不允许出理重复的。

         4)break作用是结束switch开关语句。

         5)在一些特殊的情况下,可以写成:

         …

          case 常量n:

          case 常量n+1:

               语句

               [break;]

         …

例:命令行传1个参数,要求是0至100之间的数,不是整数的话就退出JVM,传的参数大于等于90时,输出“优秀”,如果小于90大于等于70之间的数,输出“良好”,小于70大于等于60时,输出“及格”,如果小于60输出“不及格,请继续努力”。

      class Switch

      {

             public static void main(String[] args)

             {

                    System.out.println("请输入成绩!");

                    int shu=Integer.parseInt(args[0]);

                    if((args.length!=1)||(shu<0||shu>100))

                    {

                           System.err.println("输入错误,请重新执行!");

                           System.exit(-1);

                    }

                    String chengji;

                    switch(shu/10)

                    {

                           case 10:

                           case 9:

                           chengji="优秀";

                           break;

                           case 8:

                           case 7:

                           chengji="良好";

                           break;

                           case 6:

                           chengji="及格";

                           break;

                           case 5:

                           case 4:

                           case 3:

                           case 2:

                           case 1:

                           case 0:

                           chengji="不及格,请继续努力";

                           break;

                           default:

                           chengji="请输入一个1至100之间的数";

                    }

                 System.out.println("成绩:"+chengji);

             }

      }

 

你可能感兴趣的:(分支语句)