Java中switch–case的用法
switch(变量)
case : 方案。
当:变量 等于 方案值时,就执行case后面的代码,遇到break; 停止整个switch结构。
一 .结构:
switch(表达式)
{
case 常量表达式1:
语句1;
break;
…
case 常量表达式2:
语句2;
break;
default:语句;
}
二.switch-case注意事项:
1, switch(A),括号中A的取值只能是整型或者可以转换为整型的数值类型,比如byte、short、int、char、还有枚举;需要强调的是:long和String类型是不能作用在switch语句上的。
2, case后的语句可以不用大括号.
3.一旦case匹配,就会顺序执行后面的程序代码,而不管后面的case是否匹配,直到遇见break,利用这一特性可以让好几个case执行统一语句.
4. default就是如果没有符合的case就执行它,default并不是必须的.
5. break用于跳出switch和循环语句所以无break则继续执行以后分支;
列一:
条件:春 夏 秋 冬
package am;
import java.util.Scanner;
/**
-
春 夏 秋 冬
*/
public class Demo07 {public static void main(String[] args) {
System.out.println(“请输入季节”);
Scanner input = new Scanner(System.in);
String seasons = input.next();
switch(seasons){
case “春”:
System.out.println(“春意盎然”);
break;
case “夏”:
System.out.println(“夏日炎炎”);
break;
case “秋”:
System.out.println(“秋高气爽”);
break;
case “冬”:
System.out.println(“冬日暖阳”);
break;}
}
}
列二:
package com;
import java.util.Scanner;
/**
-
请输入年份:
-
请输入月份。
-
请输入日期
-
今天是这一年的第:N 天。
*/
public class Demo01 {public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(“请输入年份:”);
int year = input.nextInt();
System.out.println(“请输入月份:”);
int month = input.nextInt();
System.out.println(“请输入日期:”);
int day = input.nextInt();
// 设定一个总的日期。
int total = 0;
switch(month){
case12:
total+=30;
case 11:
total += 31;
case 10:
total += 30;
case 9:
total += 31;
case 8:
total += 31;
case 7:
total += 30;
case 6:
total += 31;
case 5:
total += 30;
case 4:
total += 31;
case 3:
if(((year % 4 == 0)&& (year % 10!=0))||year%400==0){total+=29; }else { total+=28; } case 2: total += 31; case 1: total +=day; } System.out.println(year+"年:"+month+"月"+day+"日是当年的第"+total+"天");
}
}
switch case判断成绩等级
public class Score {
private static Scanner scanner;public static void main(String[] args) {
scanner = new Scanner(System.in);
int score = scanner.nextInt();
if (score > 100 || score < 0) {
System.out.println(“输入有误”);
return;// 这里就直接退出了
}
switch (score / 10) {
case 10:
case 9:
System.out.println(“A”);
break;
case 8:
System.out.println(“B”);
break;
case 7:
System.out.println(“C”);
break;
case 6:
System.out.println(“D”);
break;
default:
System.out.println(“E”);
}
}
}