+ 11
Who can explain this code?
16 odpowiedzi
+ 12
https://www.sololearn.com/learn/Java/2145/
+ 6
Lana Mironchik because x start with 3. And this code don't have break statment. so it will enter in one of the cases and do it x+=x 3 times (x =12) and will sum with 5. For just do it one time just set break properly.
+ 4
Mbrustler, I understand that, but how did the number 17???
+ 3
That is another version of if else if statements it checks the value of x
default is excecuted if none of the cases is true
+ 3
Anya o yeah that was it normally the programm wouldnt run without break in c# that is
+ 3
If you dont put some "break" statement, also next to matched case will be executed
+ 2
Lana Mironchik if you comment the case after 3 and the default case out you should see why
+ 2
public class Switch
{
public static void main(String[] args) {
int x = 3;
switch (x){
case 1:{x+=x;}
case 3:{x+=x;}
//case 5:{x+=x;}
//default: {x+=5;}
}
System.out.println (x);
}
}
thats not how i know the case statement works but the following cases are also excecuted
+ 2
You basically forgot to use "break;" , I added some extra System.out.println so you could see exactly what your code was doing , and also added an extra switch for you to have an example code .
https://code.sololearn.com/cUXCknmi97p1/#java
+ 2
since there are no break statements the code will execute all the statements
starts with case 1:
x +=x is same as x = x + x; thus x becomes 2
case 3
2 + 2 = x; x becomes 4
case 5
4 + 4 = x ; x becomes 8
default
x += 5 -> x = x + 5
so 8 + 5 = 13
which is the answer
+ 2
Like people said before, this is because of the missing break statements.
It's called a "fall-through" and it can actually be useful if you want multiple cases to execute the same code.
Google "switch case fallthrough" if you want to know more.
+ 1
you must use “break” end of each case for ex:
case 1:
return x;
break;
+ 1
as you have given the value 1 for switch so the first condition becomes true. but after it you have not used 'break'.so compiler reads all the other conditions also so your answer is 13.if you would use 'break' in each case your answer will be of your choice.
+ 1
X+= should be read as x = x+x
Case 1 x=1+1;
Case 3 x=2+2;
Case5 x=4+4;
Default x= 8+5;
13 is answer
0
HI
0
The role of the break statement is to terminate the switch statement.
Without it, execution continues past the matching case statements and falls through to the next case statements, even when the case labels don’t match the switch variable.
This behavior is called fallthrough and modern C# compilers will not compile such code. All case and default code must end with a break statement.
so, you get the answer now 😋