请解释下面代码示例的输出“0”。在Java中使用switch case case语句中的字符串是否合法?
public class Test {
static int x;
public static void main(String[] args) {
String ss = "aBc";
String s = "ABC";
switch(s){
case "" : x++;
case "AbC" : x++;break;
case "ABC" : x--;
default : x++;
}
System.out.print(x);
}
}
答案 0 :(得分:3)
如果你没有添加中断,它会调用booth case(这是正确的)和默认值。
case "ABC" : x--;
default : x++;
所以它经历了上述案例
答案 1 :(得分:2)
你没有在案例" ABC"之后休息,所以默认也可能被执行。默认x = 0,并且执行了switch语句的这些行:
case "ABC" : x--;
default : x++;
所以,x = 0,然后在第一行之后x = -1,在第二行之后x = 0。
答案 2 :(得分:2)
您在switch
中遇到两起案件。
switch(s){
case "" : x++;
case "AbC" : x++; break;
case "ABC" : x--;
default : x++;
}
您点击了"ABC"
因为s = "ABC"
,但您没有break
,这会导致您完全离开switch
声明。因此,您还可以点击default
案例。
因此,在x
情况之后,"ABC"
设置为-1,但由于default
情况,立即设置为0。
现在,我不会说你的break
声明丢失了,因为它可能是故意的。但这是包含它们的一个很好的理由,因为如果你不这样做,你可能会变得异常。
答案 3 :(得分:2)
变量x
初始化为0
:
static int x;
与
相同static int x = 0;
然后s = "ABC"
,您到达case "ABC"
x = -1
。但是,此案例条目中没有break
,因此您继续default
执行x++
,即-1 + 1
即0
。
答案 4 :(得分:1)
是的,在Java中使用字符串是合法的,不像C只接受整数。
你有s = "ABC"
,它执行第三种和默认情况,因为你没有在第三种情况下指定break
来划分你的开关行为。因此,在x后的3rd case
x值导致x = -1,并且在默认情况下,它会增加回0.因此x的值没有从其初始值改变。
答案 5 :(得分:0)
您错过了break
声明:
// x is initialized to zero
// s = "ABC"
switch(s) {
case "": // Skipped
x++;
case "AbC": // Skipped
x++;
break;
case "ABC": // This is executed
x--; // x is now equal to 1, but there's no break statement
default: // Since there's no break statement, this block is also executed
x++; // x is now equal to 1--: 0
}
答案 6 :(得分:0)
is it legal to use string in switch case statement in Java ?
Java 7引入带有sting的switch语句。使用带有switch语句的字符串非常合法。
切换案例语法 - 您在switch语句中缺少break
switch(expression){
case value :
//Statements
break; //optional
case value :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}
我修改了第1行添加了break
关键字,在你的代码中,当第3行首先执行时它将x值0更改为-1然后第4行将执行它将x值-1更改为0,所以你的结果是“0”
public class Test {
static int x;
public static void main(String[] args) {
String ss = "aBc";
String s = "ABC";
switch(s){
case "" : x++; break; // Line 1
case "AbC" : x++;break; // Line 2
case "ABC" : x--; // Line 3
default : x++; // Line 4
}
System.out.print(x);
}
}