Reputation: 31
Switch case is taking value but only the default case is running.
int z = Integer.parseInt(x);
JOptionPane.showMessageDialog(null,+z);
switch (z) {
case ('1'):
C.SetEmpInformation();
break;
case ('2'):
C.UpdateEmpInformation();
break;
default:
JOptionPane.showMessageDialog(null, "Invalid Identity");
}
Upvotes: 0
Views: 1209
Reputation: 13195
It works for me in NetBeans too, so if it does not even start on your machine, you may have some verification tool, linter, something like that.
Anyway, what you write is correct Java code, just probably it will not do what you expect, and that is what the message may indicate.
You can switch
on numbers, characters and Strings, all of them work. Just do not mix them: they either will not compile (mixing numbers/characters with String), or will work in a probably unexpected way (mixing numbers with characters), because 1
is a number but '1'
is a character, which is represented by its ASCII code as a number, 49.
Test code:
String x="1";
int z=Integer.parseInt(x);
switch(z){
case ('1'): System.out.println(z+" is '1'");break;
default: System.out.println(z+" is not '1'");
}
x="49";
z=Integer.parseInt(x);
switch(z){
case ('1'): System.out.println(z+" is '1'");break;
default: System.out.println(z+" is not '1'");
}
x="1";
z=Integer.parseInt(x);
switch(z){
case 1: System.out.println(z+" is 1");break;
default: System.out.println(z+" is not 1");
}
switch(x.charAt(0)){
case '1': System.out.println("\"1\".charAt(0) is '1'");break;
default: System.out.println("\"1\".charAt(0) is not '1'");
}
switch(x){
case "1": System.out.println("\""+x+"\" is \"1\"");break;
default: System.out.println("\""+x+"\" is not \"1\"");
}
Output:
1 is not '1' 49 is '1' 1 is 1 "1".charAt(0) is '1' "1" is "1"
Upvotes: 0
Reputation: 15423
Remove the single quotes in your case statements. They will be matched as char
and not as int
. '1' is a character
and very different from the number 1.
switch (z) {
case 1: /* .... */
case 2: /* .... */
default : /* .... */
}
You wouldn't need the brackets as well.
Upvotes: 3
Reputation: 18568
The type you are checking in your case
statements is wrong, you compare an int
(z
) to a char
('1'
).
You need to write your case
s like this:
JOptionPane.showMessageDialog(null, + z); // btw, what is this + doing here?
switch (z) {
case 1:
C.SetEmpInformation();
break;
case 2:
C.UpdateEmpInformation();
break;
default:
JOptionPane.showMessageDialog(null, "Invalid Identity");
break;
}
Upvotes: 1