(面试)写出下面switch语句的输出结果
(1)
public static void main(String[] as)
{
int a = 0;
switch (a)
{
case 1:
System.out.println("1");
case 2:
System.out.println("2");
case 3:
System.out.println("3");
case 4:
System.out.println("4");
case 5:
System.out.println("5");
default:
System.out.println("default");
}
}
输出为:
default
(2)
public static void main(String[] as)
{
int a = 4;
switch (a)
{
case 1:
System.out.println("1");
case 2:
System.out.println("2");
case 3:
System.out.println("3");
case 4:
System.out.println("4");
case 5:
System.out.println("5");
default:
System.out.println("default");
}
}
输出为:
4
5
default
(3)
public static void main(String[] as)
{
int a = 4;
switch (a)
{
case 1:
System.out.println("1");
case 2:
System.out.println("2");
case 3:
System.out.println("3");
default:
System.out.println("default");
case 4:
System.out.println("4");
case 5:
System.out.println("5");
}
}
输出:
4
5
(4)
public static void main(String[] as)
{
int a = 3;
switch (a)
{
case 1:
System.out.println("1");
case 2:
System.out.println("2");
case 3:
System.out.println("3");
default:
System.out.println("default");
case 4:
System.out.println("4");
case 5:
System.out.println("5");
}
}
输出:
3
default
4
5
(5)
public static void main(String[] as)
{
int a = 0;
switch (a)
{
case 1:
System.out.println("1");
case 2:
System.out.println("2");
case 3:
System.out.println("3");
default:
System.out.println("default");
case 4:
System.out.println("4");
case 5:
System.out.println("5");
}
}
输出:
default
4
5
总结:
没有使用break时
(1)如果匹配到了,则按顺序执行下面的case(不管default的位置如何:若default在上面不执行,若在下面执行,作为普通的case执行)
(2)如果没有匹配到,就走default的语句,再走default下面的语句