Can you use conditional expressions on a switch in Android?

I can’t find a direct answer yes or no to this in my search. On Android, is there a way to use a conditional statement in case-switch? For example, if age is an int value:

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

I tried several ways to encode this (completely shooting in the dark) and come up with compiler errors, and I also tried the nested IF statement, but it does not support breaking, so the logic breaks and it also ends up executing ELSE code in nesting. I feel that the switch is my best bet, but I can't find an example of the correct syntax for what I'm trying to do! Any help would be greatly appreciated. All the examples that I find just use a patch case for a few things, for example, if it is 1, do it if it does 2, but without making 100 cases to check the age, I'm not sure how else this works.

+5
source share
7 answers

Not. You cannot do this

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

You need if and else ,

 if (age > 79) { // do this stuff. } else if (age > 50) { // do this other stuff. } // ... 
+5
source

Try this beautiful and 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(); 
+5
source

You cannot use this if it is an expression.

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

etc...

+1
source

If you use a loop, you can see What is the "continue" keyword and how does it work in Java? . This is not a good place to use a 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
source

each switch case must be integer or string with JavaSE 7, and you are trying to pass a boolean to it, so it is not possible. Read the oracle document to learn more about the java switch in more detail http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

0
source

You cannot use conditional statements with switch .

But you can do this with if ! If you have a loop, you can use continue to stop any upcoming lines and start at the beginning of the innermost loop.

 if(age>76){ // Code... continue; }else if(age>50){ // More Code... continue; }else{ // Even more code... continue; } 
-1
source

It can be done. The code should be slightly modified.

 public static void main(String[]arguments) { int x=1, age=55; switch(x) { case 1: if((age>=60)&&(age<200)) System.out.println("Senior Citizen"); case 2: if((age>=18)&&(age<60)) System.out.println("Adult"); case 3: if((age>=12)&&(age<18)) System.out.println("Teenager"); break; default : System.out.println("Child"); break; } } 
-3
source

Source: https://habr.com/ru/post/1203000/


All Articles