Can I jump from one case to another in a switch statements? - switch-statement

For switch statements, is it possible to change the value of the switch inside the switch statement so that it can jump around to different cases?
Ex:
int w = 0;
switch(w)
{
case 1:
doSomething();
w = 3;
case 2:
doSomething();
break;
case 3:
doSomething();
break;
}
Basically what I'm asking is, if I do not place a break statement for a case and I change the value of the switch in the same case, will the code execute both cases?

Yes you can change the value inside switch but it will not execute case for new value until you break in the case where you changed the value.
In your case it will not go in any case as there is no case for 0. But if you change to w = 1 then it will go for case 1 and then for case 2 as you do not have break; but it will not go for case 3.

No, it will not change and will not execute new case statement.
Remember that, once appropriate match is found with the case statement corresponding to a value inside the switch statement, that particular case is executed and once that is executed ( if break is provided after each case to prevent falling through all cases) , then the control returns to the end of switch statement.
Sample Code :
public class A {
public static void main(String [] args) {
int i=1;
switch(i) {
case 1 :
System.out.println("Case 1");
i = 2;
break;
case 2 :
System.out.println("Changed to Case 2");
break;
default:
System.out.println("Default");
break;
}
System.out.println("Final value of i " + i);
}
}
Output :
Case 1
Final value of i 2
Note : Inserting proper breakpoints, try to debug. You will come to know yourself, what exactly is happening.

If we do not give break after each case then Java will start executing the statement from matching case and keep on executing statements for following cases as well, until either a break statement is found or switch statements end is encountered.

If case 1 happens to execute, it's just a fall through to the case 2. And since there is a break in case 2, further fall through doesn't happen. It doesn't jump to case 3 because of the statement w = 3 ; in case 1.

No the switch's case will not change when changing the value in a particular case it checks only once
let a = 1
switch (a) {
case 1:
console.log("Hello from 1")//only this will be printed
a = 2//value of a is changed
break
case 2:
console.log("hello from 2")//this will not execute
a = 3
break
case 3:
console.log("hello from 3")//this will not execute
a = 4
break
case 4:
console.log("hello from 4")//this will not execute
break
default:
console.log("default")
}
console.log(a)//value will be 2

Related

Controling do while loop with string

Hi folks this is my question for example i have 3 articles and user can chose any one of them or all of them. In the beginning i ask a user, "do you want to choose some articles?" and if he types yes than we start a while or do while loop that adds prices of all chosen articles and adds them to the total value,
for example article one price is 20 and article 3 price is 40 it should write you have chosen articles one and article three and total price is 60. And when user ends with his choosing he types no and the loop ends.
The real question is my do while loop is always endless i don't know how to stop the loop with a String. This my 10th version of code, i tried everything but really can't solve this problem.
public static void main(String[] args) {
Scanner tastatura = new Scanner(System.in);
System.out.println("Artikal 1\nArtikal 2\nArtikal 3");
System.out.println("Do you want to chose a new article");
String choiseString = tastatura.nextLine();
do {
System.out.println("Chose article ");
int choise = tastatura.nextInt();
switch (choise) {
case 1:
System.out.println("Artikal 1 ");
int price = 10;
break;
case 2:
System.out.println("Artikal 2 ");
price= 20;
break;
case 3:
System.out.println("Artikal 3");
price = 30;
break;
}
} while (choiseString.equalsIgnoreCase("yes") );
}
I believe your issue is that you never give the opportunity for the user to change the value of choiseString.
You allow the user to set the value before the loop begins, but once inside the loop it doesn't change.
Your while loop could instead do something like:
do {
System.out.println("Do you wish to continue?");
choiseString = tastatura.nextLine();
System.out.println("Chose article ");
int choise = tastatura.nextInt();
//rest of your logic here
} while (choiseString.equalsIgnoreCase("yes") );
In this case it would then ask for 1 more choice and then exit the loop (although I haven't tested this code).
I recommend to use a boolean.
This way you will only need to check for true or false, or 1/0.
But the important part is to in some point inside the loop, set that variable to true or false, because if you don't do that, the loop will be an infinite loop.
Once you set the variable to false or true in some point inside the loop, everything will goes fine ;)
I hope this helps

Switch with multiple statements for same case

I would like to use an statement for multiple cases and then an extra statement for a single case.
switch (i)
{
case 1:
case 2:
statement1;
break;
case 1:
statement2;
break;
}
So for case 1 statement1 and statement2 should be executed.
You could delete the second case 1 in your code and move statement2 to your first case 1. But this only works if the order of the statements is not important (i.e. statement2 can be executed before statement1):
switch (i)
{
case 1:
statement2;
//Fall through
case 2:
statement1;
break;
default:
pleaseDoNotForgetMe();
}
If the order is important, I think you have no choice but give each case its break:
switch (i)
{
case 1:
statement1;
statement2;
break;
case 2:
statement1;
break;
default:
pleaseDoNotForgetMe();
}

swift case falling through

Does swift have fall through statement? e.g if I do the following
var testVar = "hello"
var result = 0
switch(testVal)
{
case "one":
result = 1
case "two":
result = 1
default:
result = 3
}
is it possible to have the same code executed for case "one" and case "two"?
Yes. You can do so as follows:
var testVal = "hello"
var result = 0
switch testVal {
case "one", "two":
result = 1
default:
result = 3
}
Alternatively, you can use the fallthrough keyword:
var testVal = "hello"
var result = 0
switch testVal {
case "one":
fallthrough
case "two":
result = 1
default:
result = 3
}
var testVar = "hello"
switch(testVar) {
case "hello":
println("hello match number 1")
fallthrough
case "two":
println("two in not hello however the above fallthrough automatically always picks the case following whether there is a match or not! To me this is wrong")
default:
println("Default")
}
case "one", "two":
result = 1
There are no break statements, but cases are a lot more flexible.
Addendum: As Analog File points out, there actually are break statements in Swift. They're still available for use in loops, though unnecessary in switch statements, unless you need to fill an otherwise empty case, as empty cases are not allowed. For example: default: break.
Here is example for you easy to understand:
let value = 0
switch value
{
case 0:
print(0) // print 0
fallthrough
case 1:
print(1) // print 1
case 2:
print(2) // Doesn't print
default:
print("default")
}
Conclusion: Use fallthrough to execute next case (only one) when the previous one that have fallthrough is match or not.
The keyword fallthrough at the end of a case causes the fall-through behavior you're looking for, and multiple values can be checked in a single case.

Switch statement bigger than

How to make a switch statement condition look like this:
if(age>18)
I want it to look like this, but then in a switch-statement version.
Is this possible?
Depends on the language you use.
C# => Not possible: switch case
Each case label specifies a constant value.
Java => Not possible: switch case
An if-then-else statement can test expressions based on ranges of
values or conditions, whereas a switch statement tests expressions
based only on a single integer
You will have to use an if-elseif-elseif-else approach in case you use Java or C#.
Javascript => Possible: switch case
case expressionN A case clause used to match against expression.
switch (true) {
case age > 18:
document.write("You are older than 18");
break;
}
mostly the switch statements are used when you are exactly matching the phrase.
switch (age>18)
{
case true:
//Do something
break;
case false:
//Do something
break;
}
In your case use if condition.It will also gives you better way to check your data.If your age is less than 18 or any other case.
if(age>18)
{/* Do something if your condition is true */ }
else
{ /* When your condition is false */ }
Yes, it's possible with a sort of 'reverse condition' trick - if that's supported by the language used, of course. That's how it looks in JavaScript:
function checkAge(age) {
switch (true) {
case age < 18:
console.log('Really young');
break;
case age < 25:
console.log('Young and proud');
break;
case age < 32:
console.log('Mature and proud');
break;
default:
console.log('Well, I got some news for you...');
}
}
checkAge(17); // Really young
checkAge(24); // Young and proud
checkAge(31); // Mature and proud
The trick is that each subsequent case value is checked against the expression specified as switch value. Still, as you need to delimit each section with break, I really doubt that's more readable than if-else statement.
You haven't specified a language, but the below construct is possible in languages which take an expression in the switch, viz:
switch (age>18)
{
case true:
// Do over 18 stuff here
break;
case false:
// Do under 18 stuff here
break;
}
Although this works, this wouldn't be an intuitive branching technique so readability of the code may suffer - use of if / then else for branches, or the conditional operator for conditional evaluation would be more common.
in php you can do:
switch($age) {
case ($age < 17):
print "do something";
break;
case ($age > 18): print "over 18"; break;
}
Technically you can put it like that (C# code sample):
switch (age) {
case 0:
case 1:
case 2:
...
case 18:
break;
default: // <- if(age>18)
...
break;
}
but do you really want it? In C#, Java etc. we usually use if else:
if (age <= 5) { // from 0 up to 5
...
}
else if (age <= 10) { // from 5 up to 10
...
}
else if (age <= 18) { // from 10 up to 18
...
}
else { // over 18
...
}
In case of a SQL dialect (where often you don't have if construction) you can put it like that:
case
when (age > 18) then
...
else...
end
for instance
select case
when (age > 18) then
'Over 18'
else
'18 or under 18'
end
from MyTable

Javascript: on/off switch

What is wrong whith this code? I have tested it many times but something still doesn't work.
var playernow = 1; //Whose player's turn it is (1 or 2)
function bobenli(playernow){
var wert="";
switch (playernow){
case "1":
wert="X";
playernow=2;
case "2":
wert="O";
playernow=1;
}
alert(playernow);
}
No break statement, both cases get executed. Also as others have said you are comparing ints to strings. You can drop the quotes in the cases.
var playernow = 1; //Welcher Spieler dran ist )(1 oder 2)
function bobenli(playernow){
var wert="";
switch (playernow){
case 1:
wert="X";
playernow=2;
break;
case 2:
wert="O";
playernow=1;
break;
}
alert(playernow);
}
var playernow = 1; //Welcher Spieler dran ist )(1 oder 2)
function bobenli(playernow){
var wert="";
switch (playernow){
case "1":
wert="X";
playernow=2;
break;
case "2":
wert="O";
playernow=1;
break;
}
alert(playernow);
}
you missed break statement in following switch case... http://jsfiddle.net/yjusC/
You need a break at the end of each case:
switch (playernow){
case "1":
wert="X";
playernow=2;
break;
case "2":
wert="O";
break;
First: no break, second: you're comparing different types (int and string). This might have no impact now, but you should be careful in general.
case "1": // This is looking for a string. You set playernow equal to an integer value above.

Resources