Can you use conditional statements in switch-case in Android?

前端 未结 7 1121
梦毁少年i
梦毁少年i 2021-02-09 16:07

I can\'t seem to find a straight forward yes or no to this in my searching. In Android, is there a way to use a conditional statement in case-switch? For example, with age being

相关标签:
7条回答
  • 2021-02-09 16:30

    You can't do this use if then statement.

    if(age > 79)
    {
       //do stuff
    }
    else if(age > 50)
    {
       //do stuff
    }
    else
    {
       /do stuff
    }
    

    etc...

    0 讨论(0)
  • 2021-02-09 16:32

    You can't use conditional statements with switch.

    But you CAN do it with if statements! If you have a loop you can use continue to stop any upcoming lines and start from the beginning of the innermost loop.

    if(age>76){
        // Code...
        continue;
    }else if(age>50){
        // More Code...
        continue;
    }else{
        // Even more code...
        continue;
    }
    
    0 讨论(0)
  • 2021-02-09 16:40

    If you are using a loop you might want to look at What is the "continue" keyword and how does it work in Java?. This is not a good place to use switch.

    if(age > 79)
    {
       //do stuff
       continue; // STOP FLOW HERE AND CONTINUE THE LOOP
    }
    else if(age > 50)
    {
       //do stuff
       continue; // STOP FLOW HERE AND CONTINUE THE LOOP
    }
    
    0 讨论(0)
  • 2021-02-09 16:44

    each case of switch is supposed to be an integer or String since JavaSE 7 and you are trying to feed a boolean value to it so its not possible .Read oracle doc to know about java switch in detail http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

    0 讨论(0)
  • 2021-02-09 16:45

    No. You cannot do this,

    switch (age){
    case (>79):
      // Do this stuff
      break;
    case (>50):
      // Do this other stuff
      break;
    }
    

    You need an if and else,

    if (age > 79) {
     // do this stuff.
    } else if (age > 50) {
     // do this other stuff.
    } // ...
    
    0 讨论(0)
  • 2021-02-09 16:50

    It is not possible. Instead, Try this minimalist approach

     age > 79 ? first_case_method() 
              : age > 50 ? second_case_method() 
              : age > 40 ? third_case_method() 
              : age > 30 ? fourth_case_method() 
              : age > 20 ? fifth_case_method()
              : ... 
              : default_case_method();
    
    0 讨论(0)
提交回复
热议问题