Javascript: on/off switch - switch-statement

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.

Related

Comparing Strings in As3

I'm currently coding a game for an assignment and I need help comparing Strings.
The question in the game asks the users to type out a specific sequence on their keyboard. I have provided a sequence "SWAGAFFAD" and I want my code to compare a the values that people might enter. If they get the sequence correct I want them to be able to proceed to the next question and if they don't type in the exact sequence they just get an error message come up. Just not sure how to code this. Can someone help me out? Assuming I'd need an IF ELSE statement??
Thanks in advance!!!
Use the == and != operators to compare strings with each other and to compare strings with other types of objects, as the following example shows:
var str1:String = "1";
var str1b:String = "1";
var str2:String = "2";
trace(str1 == str1b); // true
trace(str1 == str2); // false
var total:uint = 1;
trace(str1 == total); // true
for more detail info adobe doc
You can use ObjectUtil.compare(string1,string2). It will return 0 if both the strings are equal else 1 or -1
Yes you might want to use if-else statement and == operator as others suggested. Here's one very simple way:
var word:String = "SWAGAFFAD";
var index:int = 0;
stage.addEventListener(KeyboardEvent.KEY_UP, keyUp);
function keyUp(e:KeyboardEvent):void{
if(String.fromCharCode(e.keyCode) == word.split("")[index]){
index++;
trace("Correct letter!");
if(index == word.length){
//Player got the whole word, proceed to next one
}
}else{
//Wrong letter, do something else
}
}

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

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

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

Resources