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
Related
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();
}
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.
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.
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
I don't understand exactly how to use a function that returns a boolean. I know what it is, but I can't figure out how to make it work in my program. I'm trying to say that if my variable "selection" is any letter beween 'A' and 'I' then it is valid and can continue on to the next function which is called calcExchangeAmt(amtExchanged, selection). If it is false I want it to ask the user if they want to repeat the program and if they agree to repeat. I want it to clear the screen and restart to the main function. How do I make my program work as intended?
This is my bool function:
bool isSelectionValid(char selection, char yesNo, double amtExchanged)
{
bool validData;
validData = true;
if ((selection >= 'a' && selection <= 'i') ||
(selection >= 'A' && selection <= 'I'))
{
validData = calcExchangeAmt (amtExchanged, selection);
}
else(validData == false);
{
cout << "Do you wish to continue? (Y for Yes / N for No)";
cin >> yesNo;
}
do
{
main();
}
while ((yesNo =='y')||(yesNo == 'Y'));
{
system("cls");
}
return 0;
}
I get this warning:
warning C4800: 'double' : forcing value to bool 'true' or 'false' (performance warning)
A bool function should return true or false. I'm guessing your warning is caused by the fact that you're declaring validData as bool, but then assign it a different value (returned by calcExchangeAmt function). That value is getting converted from its value type (double) to boolean (true or false).
So, your IsSelectionValid method should just return true if selection is valid, or false if it's not. Then whatever code needs to know that information can proceed accordingly.
I don't know much C++, so forgive me for syntax problems my code is bound to have, but your code should look something like this:
bool isSelectionValid(char selection)
{
return (selection >= 'a' && selection <= 'i') || (selection >= 'A' && selection <= 'I');
}
void myCallingFunction(double amtExchanged, char selection)
{
bool isSelectionValid = isSelectionValid(selection);
if(isSelectionValid)
{
double exchangeAmt = calcExchangeAmt (amtExchanged, selection);
}
else
{
cout<<"Do you wish to continue? (Y for Yes / N for No)";
cin>>yesNo;
if((yesNo =='y')||(yesNo == 'Y'))
{
main(); // or whatever code starts another attempt
}
}
This code is seriously confusing and very non-C++ like. We normally expect main() to be the function that drives things and calls other functions, not to have it called from some other place. We generally avoid do unless there is a compelling reason (and I don't see one here). I think it's highly unlikely that a function called calcExchangeAmt returns true or false; I suspect it actually returns a number that you should be doing something else with (showing to the user?).
With all this going on, trying to explain your actual compiler error messages is of limited value. Your code is all inside out and backwards. Anna Lear's answer seems like a better starting point if it makes sense to you.
The type of 0 is not bool; true or false is bool. It is telling you that 0 is a double, but it is forcing it to a boolean type.