If-else working, switch not [duplicate] - java

This question already has answers here:
In a switch statement, why are all the cases being executed?
(8 answers)
Closed 1 year ago.
I am making an app that has a grid of images with text and each one opens a different activity. It works fine but just for design purposes I want to replace my if-else statements with switch statements (which I assume I can do) however it doesn't work. Right now my working code to set the label on each image is:
if(position == 0)
textView.setText(R.string.zero);
else if(position == 1)
textView.setText(R.string.one);
else if(position == 2)
textView.setText(R.string.two);
else if(position == 3)
textView.setText(R.string.three);
else if(position == 4)
textView.setText(R.string.four);
else if(position == 5)
textView.setText(R.string.five);
ect....
I want to use:
switch(position)
case 0:
textView.setText(R.string.zero);
case 1:
textView.setText(R.string.one);
case 2:
textView.setText(R.string.two);
case 3:
textView.setText(R.string.three);
case 4:
textView.setText(R.string.four);
but when I did that ever label was the last one that I defined (in my example it would be "four"). I also have a similar code for each object to start a different intent with the position variable however that does the opposite and makes every intent equal to the first one. Is my syntax wrong or will this not work for my situation?

You need to break; after each statement in a case, otherwise execution flows down (all cases below the one you want will also get called), so you'll always get the last case.
switch(position) {
case 0:
textView.setText(R.string.zero);
break;
case 1:
textView.setText(R.string.one);
break;
case 2:
textView.setText(R.string.two);
break;
case 3:
textView.setText(R.string.three);
break;
case 4:
textView.setText(R.string.four);
break;
}
Here's the official tutorial explaining when to and when not to use break;.

You need to break; after each branch:
switch (position) {
case 0:
textView.setText(R.string.zero);
break; // <-- here
// etc
}
Legitimate uses of switch when you don't break exist, those are called fall throughs; or because you return or throw.:
switch (someNumber) {
case 0:
return 0;
// no need for break here
case 1:
throw new IllegalArgumentException();
// no need to break here
case 2:
System.out.println("Oh, I got two!");
// fall through
case 3:
return 3;
default:
System.out.println("Meh")
// No need to break: last possible branch
}
return -1;
will return 3 even if you enter 2.
But otherwise you need to break.

Using a break statement after each case should fix the problem. I would also use a default statement as well after the last case.

This is the solution. You need to use break to avoid going through each case:
switch(position)
case 0:
textView.setText(R.string.zero);
break;
case 1:
textView.setText(R.string.one);
break;
case 2:
textView.setText(R.string.two);
break;
case 3:
textView.setText(R.string.three);
break;
case 4:
textView.setText(R.string.four);
break;
I would recommend to read the oracle documentation about the switch statement.

You need to use break statement after eace case operations. In a switch-case statement if you dont use a break statement then all the cases after that specific one will be executed also
case 0:
textView.setText(R.string.zero);
break;

Don't forget to put break; after each case: like that:
switch(position){
case 0:
textView.setText(R.string.zero);
break;
case 1:
textView.setText(R.string.one);
break;
case 2:
textView.setText(R.string.two);
break;
case 3:
textView.setText(R.string.three);
break;
case 4:
textView.setText(R.string.four);
break;
}

In the Switch-case statements, you need to put break; after each case.
switch(position){
case 0:
textView.setText(R.string.zero);
break;
case 1:
textView.setText(R.string.one);
break;
case 2:
textView.setText(R.string.two);
break;
case 3:
textView.setText(R.string.three);
break;
case 4:
textView.setText(R.string.four);
break;
default:
System.out.println("not available");
}
Also you need to put default: at last, because when all case are wrong that time perform default: action.
In the switch-case statement not forgot about break; and default action.

Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.
Switch is faster than if-else statement
Bottom line : Default is optional(works like else statement in switch), Break is mandatory.
Interesting fact: you won't see any compilation error, even if you forgot to place the break statement.

The switch needs a break with in each case. But in your case it could be done much simpler by defining an array as shown below.
String values = {R.string.zero, R.string.one, R.string.two, ... };
Use this to populate textView : textView.setText(values[position]);

Related

in switch function how get case value in every case block

I’m using switch in my code and i wanna get case value in every case block. how can i get it?
switch(value)
{
case Value1:
function1(Value1);
// i want something like this : function1(getCaseValue)
break;
case Value2:
function1(Value2);
break;
case Value3:
function2(Value3);
break;
}
Inside of your case statements, you can call function with value variable function1(value). Here is full code:
switch(value) {
case Value1:
function1(value);
break;
case Value2:
function1(value);
break;
case Value3:
function2(value);
break;
}
If you will always call same function in specific set of values, you can even make your switch-case statements simpler:
switch(value) {
case Value1:
case Value2:
function1(value);
break;
case Value3:
function2(value);
break;
}
If you have the same handling for different cases, instead of duplicating the handling, you can write clearer, simpler code by combining them like this:
switch (value) {
case 0:
case 1:
case 2:
function1(value);
break;
}
If you want to add additional handling for other cases, add them, too:
case 3:
function2(value);
break;
and maybe inlude a default:
default:
function3(value);

Does a java switch case statement execute multiple cases for negative int values?

I just run over something strange in my java code:
switch (result) {
case 0:
result_amount = 500;
case 1:
result_amount = 600;
case -1:
result_amount = 700;
}
result is from primitive type int.
For value 1 case 1 and case -1 are executed.
Is this a normal switch case behaviour? If yes: why?
You need to use the break keyword after a case block:
switch (result) {
case 0:
result_amount = all_amounts[i];
break;
case 1:
result_amount = all_amounts[i];
break;
case -1:
result_amount = all_amounts[i+1];
}
The switch statement will make a jump to the correct case tag, then execute all the code that follow, ignoring potential other case tags. You can consider the switch statement just like a goto one.
Fall Through.
quoting from docs
The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.
You have to add the break after each case.
case 1:
result_amount = 600;
break;
Remember:
This is a mistake that almost every beginner will make. That's why I like C# more. It doesn't allow "fall-through".
What you did wrong is you fell-through the switch statement. Try using 0 as the value of result. It will go through all the cases. When a switch case finishes execution, the next case gets executed. That's why we need to add a break; statement for each case of the switch statement.
switch (result) {
case 0:
result_amount = 500;
break;
case 1:
result_amount = 600;
break;
case -1:
result_amount = 700;
break;
}
But sometimes we want fall-through. For example when we want to calculate number of days in a month:
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
break;
case 2:
days = 28;
case 4:
case 6:
//Lots of code...
}
Without break statement next cases will be executed.
Generally Case Label Should be Integer / Constant
Negative numbers having no decimal point are also considered as Integer
Thus it is not necessary to have Case Labels greater than Zero
This is fall through condition.
switch (result) {
case 0:
result_amount = all_amounts[i];
case 1:
result_amount = all_amounts[i];
case -1:
result_amount = all_amounts[i+1];
}
To avoid it you must put break statement
switch (result) {
case 0:
result_amount = all_amounts[i];
break;
case 1:
result_amount = all_amounts[i];
break;
case -1:
result_amount = all_amounts[i+1];
break;
}
Now only matching case will be executed.
You should include break and default to run program in a proper way. Let me give you a example of it.
switch (result) {
case 0:
result_amount = 500;
break;
case 1:
result_amount = 600;
break;
case -1:
result_amount = 700;
break;
}

Java switch case fall through

I have a switch case in Java like this:
switch(int example)
{
case 1: //Do different
break;
case 2: //Do different
break;
/** For int more than 2, then I need
for it to do something same.
*/
case 3://Do different and case6
break;
case 4://Do different and case6
break;
case 5://Do different and case6
break;
case 6:
break;
}
What is an elegant way to do this, sans having a special case 6 function that case 3-5 calls? (I use int here, but that is an example, so I can't use if(int >2))
A switch can't really do exactly what you are asking out of the box. You can construct something like this with a nested switch though:
outer_switch: switch (example) {
case 1: System.out.println("1");
break;
case 2: System.out.println("2");
break;
default: {
switch (example) {
case 3: System.out.println("3");
break;
case 4: System.out.println("4");
break;
case 5: System.out.println("5");
break;
case 6: System.out.println("6");
break;
default: break outer_switch;
}
System.out.println("not 1 nor 2");
}
}
Note the labeled break on outer_switch which is a way to circumvent the shared code if example does not meet any of the inner cases.
One way I could think of is to move your code to different functions. Something like this.
void case1(){
// do something
}
...
void case3(){
// do something
case6();
}
...
void case6(){
// do something
}
// This switch is in some other method.
switch(int example)
{
case 1: //Do different
case1();
break;
...
case 3://Do different and case6
case3(); //internally calls case 6
break;
...
case 6:
case6();
break;
}
Or you can even have different methods for each case and call case3() and case6() methods in the case 3:. Either way, the methods solutions would work, and IMHO, it would be a bit more elegant and multiple switch statements.
I'm not sure if it's elegant, but one way would be to have two switch blocks:
switch(int example)
{
case 1: //Do different
break;
case 2: //Do different
break;
case 3:
// Do whatever
break;
case 4:
// Do whatever
break;
case 5:
// Do whatever
break;
}
switch(int example)
{
case 3:
case 4:
case 5:
case 6:
// Do whatever (case 3-5 fall through)
break;
}
Although your code is not pretty it's probably going to give you decent performance. Your other obvious option is an if-elseif-else statement. See the accepted answer here for why switch might be the best option, and here to see what performance issues you might run into with large switch statements in Java.
This might also be a solution to what you want to achieve:
switch(example){
case 1:
System.out.println(example);
break;
case 2:
System.out.println(example);
break;
case 3:
System.out.println("I'm case 3");
case 4:
if (example == 4){
System.out.println("I'm case 4");
}
case 5:
if (example == 5){
System.out.println("I'm case 5");
}
case 6:
System.out.println("I'm in extra case " + example);
break;
}
The idea is that you add an extra condition check to let your code fall through all the branches without executing unnecessary ones.

Java: Can I fall through only one case in a switch statement

In Java, can I fall through only one of the cases in a switch statement? I understand that if I break, I will fall through to the end of the switch statement.
Here's what I mean. Given the following code, on case 2, I want to execute case 2 and case 1. On case 3, I want to execute case 3 and case 1, but not case 2.
switch(option) {
case 3: // code
// skip the next case, not break
case 2: // code
case 1: // code
}
No, what you are after is not possible with a switch statement. You will fall through each case until you hit a break. Perhaps you want case 1 to be outside of your switch statement, so that it is executed regardless.
Put the code into methods and call as appropriate. Following your example:
void case1() {
// Whatever case 1 does
}
void case2() {
// Whatever case 2 does
}
void case3() {
// Whatever case 3 does
}
switch(option) {
case 3:
case3();
case1();
break;
case 2:
case2();
case1();
break;
case 1:
case1(); // You didn't specify what to do for case 1, so I assume you want case1()
break;
default:
// Always a good idea to have a default, just in case demons are summoned
}
Of course case3(), case2()... are very poor method names, you should rename to something more meaningful about what the method actually does.
My suggestion is to not use fallthrough for anything except cases like the following:
switch (option) {
case 3:
doSomething();
break;
case 2:
case 1:
doSomeOtherThing();
break;
case 0:
// do nothing
break;
}
That is, giving several cases the exact same block of code to handle them (by "stacking" the case labels), making it more or less obvious what the flow is here. I doubt most programmers intuitively check for case fall through (because the indentation makes a case look like as a proper block) or can efficiently read code that relies on it - I know I don't.
switch(option)
{
case 3:
...
break;
case 2:
...
break;
}
... // code for case 1
You can custom the condition if you want to split cases
const { type, data } = valueNotifications
let convertType = ''
if (data?.type === 'LIVESTREAM' && type === 'NORMAL') {
convertType = 'LIVESTREAM1'
} else convertType = type
switch (convertType)
My use case has split the type from value notifications, but I have a specific LiveStream case which only shows in data.type is 'LIVESTREAM'
Something like this maybe.
switch(option) {
case 3: // code
// skip the next case, not break
// BLOCK-3
case 2: // code
if(option == 3) break;
// BLOCK-2
case 1: // code
// BLOCK-1
}
In switch statement if you don't break the subsequent case is executed. To give you simple example
int value = 2;
switch(value) {
case 1:
System.out.println("one");
break;
case 2:
System.out.println("two");
case 3:
System.out.println("three");
break;
}
Will output
two
three
Because break wansn't executed on case 2

Can I use OR statements in Java switches?

I'm wondering if I can use or in switch-case in Java?
Example
switch (value)
{
case 0:
do();
break;
case 2 OR 3
do2();
break;
}
There is no "or" operator in the case expressions in the Java language. You can however let one case "fall through" to another by omitting the break statement:
switch (value)
{
case 0:
do();
break;
case 2: // fall through
case 3:
do2();
break;
}

Categories

Resources