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 an int value:
switch (age){
case (>79):
// Do this stuff
break;
case (>50):
// Do this other stuff
break;
etc, etc
I've tried several ways to code this (completely shooting in the dark) and come up with compiler errors, and I've also tried a nested IF statement, but it doesn't support break so the logic breaks down and it ends up also executing ELSE code lower in the nesting. I feel like switch-case 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 appreciated. All the examples I find just use switch-case for a few things like if it is a 1 do this, if it's a 2 do that, but without making 100 case statements to check against age, I'm not sure how else to work this.
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.
} // ...
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();
You can't do this use if then statement.
if(age > 79)
{
//do stuff
}
else if(age > 50)
{
//do stuff
}
else
{
/do stuff
}
etc...
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
}
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
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;
}
It can be done.
The code needs to be slightly altered.
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;
}
}
Related
Good Evening,
I created this method for a class. I used a switch/case to execute depending on the value of expression. I included an if-else method for each case. I do get an error on case 1-> switch rules are a preview feature and are disabled by default. I attempted to add a : after case 1 and case 2but my results reached high numbers for the sets. I changed the : to -> and it worked appropriately. Now I am wondering if this was a proper way to set the case statements or should it be written differently.
private void playGame()
{
double winCheck = Math.random();
switch (matchServer) {
case 1 ->{
if (winCheck <= player1WinProb)
player1GamesWon++;
else
player2GamesWon++;
matchServer = 2;
}
case 2 ->{
if (winCheck <= player2WinProb)
player2GamesWon++;
else
player1GamesWon++;
matchServer = 1;
A correct switch statement must use ':'
Also, 'break' is missing. This to avoid executing next cases.
You can add 'default' that means that case 1 and case 2 were not presented.
switch (matchServer) {
case 1:
if (winCheck <= player1WinProb)
player1GamesWon++;
else
player2GamesWon++;
matchServer = 2;
break;
case 2:
if (winCheck <= player2WinProb)
player2GamesWon++;
else
player1GamesWon++;
matchServer = 1;
break;
default:
//If it was not 1 or 2
//Printing the values can help
}
I am working on an exercise, where I have to select a category(genre) of movie and based on my selection, the program will return a list of movies in that category from an ArrayList of objects.
My program works when typing out a category in string format. However I am trying to use a try catch block to also allow category selection by number.
My catch block is working, however my try block is not and returns nothing. Can someone help me determine what is wrong with my code? I am guessing there is something wrong with my parseInt assignment?
System.out.print("What category are you interested in?");
String catSel = sc.next();
try //Check category for Integer, otherwise catch
{
int numSel = Integer.parseInt(catSel);
if(numSel == 1)
{catSel = "animated" ;}
if(numSel == 2)
{catSel = "drama";}
if(numSel == 3)
{catSel = "horror";}
if(numSel == 4)
{catSel = "scifi";}
if(numSel == 5)
{catSel = "musical";}
if(numSel == 6)
{catSel = "comedy";}
else catSel = "";
//Check each movie for chosen category
for(int x = 0; x < list.size() - 1; x++)
{
if(catSel.equals(list.get(x).category))
System.out.println(list.get(x).movie);
}
}
catch (NumberFormatException e)
{
//Check each movie for chosen category
for(int x = 0; x < list.size() - 1; x++)
{
if(catSel.equals(list.get(x).category))
System.out.println(list.get(x).movie);
}
}
the way your if-clauses are structured, the else clause will be called whenever numSel is not 6, replacing catSel with the empty string.
You may want to add an else after each if block or replace all of them with a switch statement.
As #Dragondraikk suggested your if-else clauses are structured in a way which is not as per your expected result .
So either use in this way :
if(someCondition){
}
else if(someCondition){
}
...........................
do whatever you want to do
...........................
else{
}
Below is the way to use Switch Statement
switch(Integer.parseInt(catSel)){
case 1 :
do Something....
break;
case 2 :
do Something....
break;
case 3 :
do Something....
break;
case 4 :
do Something....
break;
case 5 :
do Something....
break;
case 6 :
do Something....
break;
default :
catSel="";
break;
}
Note : You can use try-catch block around this
Update
Advantage of Using Switch over If else
The problem with the if...else if... chain is readability , I have to look at every single if condition to understand what the program is doing. For example, you might have something like this:
if (a == 1) {
// stuff
} else if (a == 2) {
// stuff
} else if (a == 3) {
// stuff
} else if (b == 1) {
// stuff
} else if (b == 2) {
// stuff
}
(obviously, for a small number of statements like this, it's not so bad)
but I'd have no way of knowing that you changed condition variable half-way through without reading every single statement. However, because a switch limits you to a single condition variable only, I can see at a glance what's happening.
Another advantage is JumpTable
A switch is often compiled to a jump-table (one comparison to find out which code to run), or if that is not possible, the compiler may still reorder the comparisons, so as to perform a binary search among the values (log N comparisons). An if-else chain is a linear search .
Here is more about Switch Statement
I have an int, int minion1Hp, which can be a value of 0 -> 20. Depending on the value it is, a certain image resource will be set for an ImageView, using bar1.setImageResource(R.drawable.hpa);. However, my code currently looks like this:
if (minion1Hp == 0) {
bar1.setImageResource(R.drawable.hp);
}
if (minion1Hp == 1) {
bar1.setImageResource(R.drawable.hpa);
}
if (minion1Hp == 2) {
bar1.setImageResource(R.drawable.hpb);
}
if (minion1Hp == 3) {
bar1.setImageResource(R.drawable.hpc);
}
if (minion1Hp == 4) {
bar1.setImageResource(R.drawable.hpd);
}
if (minion1Hp == 5) {
bar1.setImageResource(R.drawable.hpe);
}
... and so on. Is there a more efficient way of doing this, rather than a long list of if statements?
Suggestion: initialize a map at startup (say in onCreate()). Like this:
mDrawables = new HashMap<Integer, Integer>();
mDrawables.put(0, R.drawable.hp);
mDrawables.put(1, R.drawable.hpa);
...
then just do:
bar1.setImageResource(mDrawables.get(minion1Hp));
You can use a switch statement with a separate case for each instance. On a side note, you shouldn't be using just if statements up there, your code will run slowly, you should be using else if to make it run faster (since your hp can never be 1 and 2 at the same time.
Ex for switch statements:
switch (minion1Hp){
case 1:
bar1.setImageResource(R.drawable.hp);
break;
case 2:
bar1.setImageResource(R.drawable.hpa);
break;
etc.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
An improvement here would be to change each if after the first one to an else if as minion1Hp can't be multiple values at the same time, but you might find it slightly neater to have the whole thing in a switch-case block instead.
I'm making a game in Slick2D and I have a lot of 'if' statements and I want to get rid of that. Now this is my code:
if((playerPositionX>570 && playerPositionX<835) && (playerPositionY>16 && playerPositionY<260)){
g.setColor(Color.red);
g.drawString("Ready to play? press enter!", 400,350);
}
Everything is fine but I have like 8 and going up of these, obviously with different coordinates.
So I would like to know if it's possible to use a switch and case method to fix this.
You can't use a Switch with ranges as cases. In other words, something like this:
Switch(playerPosition)
case 570-835:
....
doesn't exist. You could do:
int num;
if (playerPositionX>570 && playerPositionX<835){
num = 0;
if (playerPositionX>836 && playerPositionX<1000){
num = 1;
and then
Switch(num){
case 0:
...
case 1:
...
but you'll still have to use the if statements.
I wrote a 'setX' method in Java that says that if x value ( (x,y) ) is negative, the value of x wont be change, and the main() will continue as usual.
void setX (int num)
{
if (num < 0)
break;
else
{
_x = num;
}
}
Am I right ?
I am not sure because of the break issue, is the break statement just break from the current method ?
thnx
break is used only in loops (while, for).
If you want to exit the method, use return instead.
Perhaps you meant
public void setX(int x) {
if (x >= 0)
_x = x;
}
you should use return. break is to break loops.
Use return; here. break is used to break out of loops.
According to the Java tutorial, break is for use with switch, for, while, and do-while loops. It doesn't go in if statements. For a switch the break keeps the switch from falling through to the next case, which it would otherwise do. For loops it stops looping regardless of the loop guards.
A break statement can either be unlabeled, in which case it goes to where control would normally resume after the switch or loop, or labeled, in which case it goes to the label (almost as if it were a goto with strict constraints on where it can come from).
To get out of the current method, use return. A return with no value is the proper statement to leave a void method.
That looks like it should work, but the break really isn't doing anything anyway. why not just if(num>=0) _x = num;
I think your intention might be a bit clearer if your logic was reversed;
void setX (int num)
{
if (num >= 0)
_x = num;
}