需求:输入一到七的任意一个数,输出该数字对应的星期数。
使用Switch语句:
1 import java.util.Scanner; 2 3 public class Main { 4 public static void main(String[] args) { 5 Scanner sc = new Scanner(System.in); 6 System.out.println("请输入一个星期数(1-7):"); 7 int week = sc.nextInt(); 8 9 switch (week){ 10 case 1: 11 System.out.println("星期一"); 12 break; 13 case 2: 14 System.out.println("星期二"); 15 break; 16 case 3: 17 System.out.println("星期三"); 18 break; 19 case 4: 20 System.out.println("星期四"); 21 break; 22 case 5: 23 System.out.println("星期五"); 24 break; 25 case 6: 26 System.out.println("星期六"); 27 break; 28 case 7: 29 System.out.println("星期日"); 30 break; 31 default: 32 System.out.println("您输入的星期数有误!"); 33 break; 34 } 35 } 36 }
结果:
使用if语句:
1 import java.util.Scanner; 2 3 public class Main { 4 public static void main(String[] args) { 5 Scanner sc = new Scanner(System.in); 6 System.out.println("请输入一个星期数(1-7):"); 7 int week = sc.nextInt(); 8 9 if (week == 1){ 10 System.out.println("星期一"); 11 }else 12 if (week == 2){ 13 System.out.println("星期二"); 14 }else 15 if (week == 3){ 16 System.out.println("星期三"); 17 }else 18 if (week == 4){ 19 System.out.println("星期四"); 20 }else 21 if (week == 5){ 22 System.out.println("星期五"); 23 }else 24 if (week == 6){ 25 System.out.println("星期六"); 26 }else 27 if (week == 7){ 28 System.out.println("星期日"); 29 }else { 30 System.out.println("您输入的星期数有误!"); 31 } 32 } 33 }
结果:
标签:week,case,Java,System,break,Switch,007,println,out From: https://www.cnblogs.com/yiqiesuifeng/p/17703438.html