Why is this switch case not working in Netbeans?

你离开我真会死。 提交于 2020-05-17 06:55:34

问题


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");
}

回答1:


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.




回答2:


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 cases 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;
}



回答3:


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"


来源:https://stackoverflow.com/questions/52907617/why-is-this-switch-case-not-working-in-netbeans

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!