首页 > 代码库 > switch语句
switch语句
-----------siwuxie095
switch语句称为情况选择语句,又称开关语句
switch是分支语句的一种,用于对多种情况进行不同处理的语句
JDK1.7之前的switch语句限定对整型数据进行判断
使用格式:
如:
代码:
package com.siwuxie095.test;
import java.util.Scanner;
public class Test21 {
public static void main(String[] args) { Scanner scanner=new Scanner(System.in); System.out.println("请输入5分制分数:"); int score=scanner.nextInt(); switch (score) { case 5: System.out.println("优秀"); break; case 4: System.out.println("良好"); break; case 3: System.out.println("及格"); break;
//case语句:如果几种情况是一种处理的代码 case 2: case 1: case 0: System.out.println("不及格"); break; default: System.out.println("输入的不是5分制分数"); break; } }
} |
运行一览:
再如:如果在case语句后不加 break 命令
代码:
package com.siwuxie095.test;
public class Test22 {
public static void main(String[] args) { int score=4; switch (score) { case 5: score++; case 4: score++; case 3: score++; case 2: score++; case 1: score++; case 0: score++; default: System.out.println(score); } }
} |
运行一览:
从 case 4 开始,由于没有 break 命令,一路贯穿到 default
再如:
代码:
package com.siwuxie095.test;
import java.util.Scanner;
public class Test23 {
public static void main(String[] args) { Scanner scanner=new Scanner(System.in); System.out.println("请输入分数等级:"); char grade=scanner.next().charAt(0); switch (grade) { case ‘优‘: System.out.println(5); break; case ‘良‘: System.out.println(4); break; case ‘中‘: System.out.println(3); break; case ‘差‘: System.out.println(2); break; default: System.out.println("输入等级错误"); break; } }
} |
运行一览:
再如:
代码:
package com.siwuxie095.test;
import java.util.Scanner;
public class Test24 {
public static void main(String[] args) { Scanner scanner=new Scanner(System.in); System.out.println("输入月份:"); int month=scanner.nextInt(); switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: System.out.println("31天"); break; case 2: System.out.println("28天"); break; case 4: case 6: case 9: case 11: System.out.println("30天"); break;
default: System.out.println("输入月份错误"); break; } }
} |
运行一览:
【made by siwuxie095】
switch语句