switch 在程序设计中也经常被使用到,其语法为
switch(object)
{
case 1:
statement
break;
case 2:
statement1
break
.
.
}
下面我们就同过一个范例来理解switch语句的使用方法,其范例目的是,根据用户输入的月份,来判断有多少天,例如,输入1,3,5,7,8,10,12 就会输出31天,要是用户输入的是2,4,610,就会输出30天,要是用户输入的是2,就会输出28,或29天,
范例1:
import java.io.*;
public class tingting8
{
public static void main(String args[]) throws IOException
{
BufferedReader buf=new BufferedReader(new InputStreamReader(System.in));
String a;
int b;
int theday=0;
int year=2006;
System.out.println("please input the month number");
a=buf.readLine();
b=Integer.parseInt(a);
if(b>12||b<0)
{
System.out.println("input error ,you must input 0 to 12");
}
else
{
switch(b)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
theday=31;
break;
case 4:
case 6:
case 9:
case 11:
theday=30;
break;
case 2:
if((year%4==0)||(year%400==0))
theday=29;
else
theday=28;
}
}
System.out.println("theday ="+theday);
}
}