0

I'm writing some programs.Im going to use this programs to tell the situation of the connection. I would only use if-else, and now I want to learn how to use switch case,but I found switch case dont use boolean,The following is what I wrote judgment formula:

if(isConnected) {
    //if connection established 
    btnwifi.setText("Connection");
} else {  
    btnwifi.setText("Unconnected");
}
Mojo Risin
  • 8,136
  • 5
  • 45
  • 58
  • 1
    switch does not allow long, float, double or boolean values in Java! You can use enum if a variable can take two or more values.. For boolean's if else is better. – Mohammed Ali Nov 15 '14 at 14:32
  • 1
    Extended on @MohammedAli you can't do switch on any primitives. Enums were worked into switches and allow more explicit declarations. – zgc7009 Nov 15 '14 at 14:35
  • Enums are best used with switch. And also see this: http://stackoverflow.com/questions/5141830/switch-expression-cant-be-float-double-or-boolean – Mohammed Ali Nov 15 '14 at 14:39

3 Answers3

0

I am not sure why you want to implement it this way. See link for boolean type in java why java takes only true of false

For switch, you may refer to this oracle doc

if you are so into switch, create a function which converts a boolean type to static constants of byte, short, char, int or string type and then use that in your switch statement though i won't recommend doing so.

Community
  • 1
  • 1
nathandrake
  • 427
  • 1
  • 4
  • 19
0

This is not what switch is intended for and is not supported in Java.

The if statement is used to control program flow based on boolean values and works perfectly, so why try to use something else? If you want to learn about switch statements your first port of call would be to learn where they are, and are not meaningful!

StuPointerException
  • 7,117
  • 5
  • 29
  • 54
0

You want learn switch.
You can use enums for your purpose,

public enum BtnWifi { // you can create new enum java file for this
 CONNECTED, NOT_CONNECTED
}
//.... Setting value for enum in your code
BtnWifi btnWifi;
if(isConnected) {
//if connection established 
   btnWifi = BtnWifi.CONNECTED;
} else {     
   btnWifi = BtnWifi.NOT_CONNECTED;
}
// No switch to use it...
switch(btnWifi) {
  case CONNECTED:
     //code for connected...
   break;
  case NOT_CONNECTED:
     //code for Not connected...
   break;
}
Mohammed Ali
  • 2,758
  • 5
  • 23
  • 41