Switch case必须与break一起使用
Break 是跳转语句。与switch case连用的时候是跳出最近的{}。
static void Main(string[]args )
{
//switch case 多用于年月日的计算
int cs=1;
switch(cs)//小括号内是一个数据类型的值
{
//case 后加空格,之后写上跟上面小括号内对应类型可能出现的值
case 1://cs值为1,则进行着一步,显示case 1
Console.WriteLine("case 1");
break;//距离break最近的大括号,跳出这个大括号,执行大括号之后的命令
case 2:
Console.WriteLine("case 2");
break;
default://如果值跟上面的case 1,case 2都不匹配,则进行这一步
Console.WriteLine("default case ");
break;
}
console.ReadLine();
}
练习
//输入日期,判断是今年的第几天············
//1 3 5 7 8 10 12
//4 6 9 11
//2
int m1 = 31, m3 = 31, m5 = 31, m7 = 31, m8 = 31, m10 = 31, m12 = 31, m4 = 30, m6 = 30, m9 = 30, m11 = 30, m2 = 28;
Console.WriteLine("输入要查询的月份");
int m = int.Parse(Console.ReadLine());
Console.WriteLine("输入要查询的日期");
int day = int.Parse(Console.ReadLine());
switch (m)
{
case 1:
Console.WriteLine("您输入的日期是" + m + "-" + day + "是今年的第" + day + "天");
break;
case 2:
Console.WriteLine("您输入的日期是" + m + "-" + day + "是今年的第" + (m1 + day) + "天");
break;
case 3:
Console.WriteLine("您输入的日期是" + m + "-" + day + "是今年的第" + (m1 + m2 + day) + "天");
break;
case 4:
Console.WriteLine("您输入的日期是" + m + "-" + day + "是今年的第" + (m1 + m2 + m3 + day) + "天");
break;
case 5:
Console.WriteLine("您输入的日期是" + m + "-" + day + "是今年的第" + (m1 + m2 + m3 + m4 + day) + "天");
break;
case 6:
Console.WriteLine("您输入的日期是" + m + "-" + day + "是今年的第" + (m1 + m2 + m3 + m4 + m5 + day) + "天");
break;
case 7:
Console.WriteLine("您输入的日期是" + m + "-" + day + "是今年的第" + (m1 + m2 + m3 + m4 + m5 + m6 + day) + "天");
break;
case 8:
Console.WriteLine("您输入的日期是" + m + "-" + day + "是今年的第" + (m1 + m2 + m3 + m4 + m5 + m6 + m7 + day) + "天");
break;
case 9:
Console.WriteLine("您输入的日期是" + m + "-" + day + "是今年的第" + (m1 + m2 + m3 + m4 + m5 + m6 + m7 + m8 + day) + "天");
break;
case 10:
Console.WriteLine("您输入的日期是" + m + "-" + day + "是今年的第" + (m1 + m2 + m3 + m4 + m5 + m6 + m7 + m8 + m9 + day) + "天");
break;
case 11:
Console.WriteLine("您输入的日期是" + m + "-" + day + "是今年的第" + (m1 + m2 + m3 + m4 + m5 + m6 + m7 + m8 + m9 + m10 + day) + "天");
break;
case 12:
Console.WriteLine("您输入的日期是" + m + "-" + day + "是今年的第" + (m1 + m2 + m3 + m4 + m5 + m6 + m7 + m8 + m9 + m10 + m11 + day) + "天");
break;
default:
Console.WriteLine("您的输入有误");
break;
}