Error in switch statement, Javascript - javascript

I got a function that should return a result depending on a dealed Black Jack hand. I used a switch statement for this, eventhough I'm not sure you could use multiple switch in a function. Anyhow I got an error saying 'missing ; before statement' after the first 'result' text in the first 'case'. This code is what I have been taught so I'm not sure where I did go wrong. Could you please give me a hint or anything, please? Refards, Thomas.
function printResult(playResult, dealResult) {
var text = "";
switch(playResult) {
case (playResult == 21) : result "black jack";
break;
case (playResult > 21) : result "busted";
break;
case (playResult < 21) : result "safe";
break;
}
switch(dealResult) {
case (dealResult < 17) : result "safe";
break;
case (dealResult == 17 && < 21) : result "stop";
break;
case (dealResult == 21) : result "black jack";
break;
}
return result;
}
var result = "Player: " + playResult + ", Dealer: " + dealResult;
ANSWER = (printResult(5+9+10, 6+3+7));

Maybe you want result to be a variable assigment?
result = "black jack"
or maybe a return?
return "black jack"

It looks like you're trying to do "if logic" in the case statement; that's not how a switch works. A switch is going to take the value of dealResult and do a straight compare.
switch(dealResult)
{
case 21: //dealResult MUST be 21
result = 'blackjack!'
break;
case 20: //dealResult MUST be 20
//etc..
break;
case >20: //not valid, will break
}
As far as I know, if you need to do > and < compares, you should be using an if -> else block.

You have to remove all of the playResult variables inside of the switch block.
In addition, switch does not support higher than or lower than so a if is better suited for this situation.
function printResult(playResult, dealResult) {
var result;
if(playResult == 21) {
result = "black jack";
} else if(playResult > 21) {
result = "busted";
} else {
result = "safe";
}
if(dealResult < 17) {
result = "stop";
} else if(dealResult == 17 && dealResult < 21) {
result = "stop";
} else {
result = "black jack";
}
return result;
}
var result = "Player: " + playResult + ", Dealer: " + dealResult;
ANSWER = (printResult(5+9+10, 6+3+7));
This is a lot closer, but there is still problems with your logic.

Looking at your function, even if you get the switch working i don't think the logic is what you're aiming it to be.
If the purpose of the function is tell you who won the game, ergo the result as your name implies then you need to first put the rules down.. lets just for readability write it in pseudo..
Where either player has blackjack check the following
Player Blackjack to Dealer Blackjack = Push (Draw)
Player Blackjack to Dealer Anything = Player Win
Player Anything to Dealer Blackjack = Dealer Win
Then check if one is bust, to win a player must of held
Player > 21 = Dealer Win
Player <=21 and Dealer > 21 = Player Win
After that, we can do the simple checks.
Player == Dealer = Push
Player > Dealer = Player Win
Player < Dealer = Dealer Win
You can't really use a switch statement effectively to do this. You 'can' use it but for something like this, if else will suffice.
function blackJackWinnerIs(player, dealer)
{
if((player == 21) || (dealer==21))
{
if(player > dealer)
return "Player";
else if (player < dealer)
return "Dealer";
else
return "Push";
}
else if(player > 21)
return "Dealer";
else if(dealer > 21) // already checked if player<=21
return "Player";
else if(player > dealer)
return "Player";
else if(dealer > player)
return "Dealer";
else return "Push";
}
var hands = [
{player:21,dealer:21},
{player:20,dealer:21},
{player:21,dealer:17},
{player:22,dealer:17},
{player:17,dealer:22},
{player:19,dealer:18},
{player:18,dealer:20},
{player:20,dealer:20}
];
for(var i=0; i<hands.length;i++)
{
var winner = blackJackWinnerIs(hands[i].player,hands[i].dealer);
console.log("Player:",hands[i].player," Dealer:",hands[i].dealer," => Winner:",winner);
}
This is functional.. but it won't protect you from bad inputs e.g. if you accidentally passed in two nulls you would get a "push" result when really you should either send out an error or void the game... but thats all on you.

Related

Javascript : problem with while loop that does not work

In the script below, I'm trying to get a function to find a random number chosen by the system. To help me to find the number :
When the number to find is smaller than what I enter on the interface: I get a message that the number to find is smaller
When the number to find is bigger than the one I enter on the interface: I receive a message that the number to find is bigger
When I find the number, I receive a message telling me that I have found the number in xxx tries. When I find the number in one go, I want to change trial by trial in the message
When I rotate the code below I just have a box to ask me what is the number to guess. Then nothing happens. Can you please help me to fix the code problems in my script below. Could you please also indicate if my approach is correct to count the number of attempts in the code below. How would you proceed ?
function askValue() {
var answer = window.prompt(
"Guess the number, enter a number between 1 and 10"
);
// keep the answer to use it in the loop
if (!answer || isNaN(answer)) {
console.log("Please enter a valid number");
} else {
return answer;
}
}
function guessnumber() {
var secret_number = Math.floor(Math.random() * 10) + 1;
var guess = askValue();
var attempts;
var i = 0;
var resultMessage = "You won, you take";
while (win == false) {
attempts++;
if (guess < secret_number) {
console.log("The secret number is bigger");
i++;
} else if (guess > Secret_number) {
console.log("The secret number is smaller");
i++;
} else if (guess == secret_number) {
win = true;
}
console.log(resultMessage);
}
}
// call the function
guessnumber();
I make your code works by fixing many mistake and bugs some of them:
using var which is old and it's better use the keyword let to declare variable!
checking if the number between 1 & 10: if (+answer < 1 || +answer > 10)
prefix +, is just shorthand for parseInt() function to convert string to number, since prompt return string not number
many more...
if you don't understand sth do a comment and I will explain to you!
function askValue() {
let answer = window.prompt(
"Guess the number, enter a number between 1 and 10"
);
// keep the answer to use it in the loop
if (!answer || isNaN(answer)) {
alert("Please enter a valid number");
} else if (+answer < 1 || +answer > 10) {
alert("Please enter a number between 1 and 10");
} else {
return +answer;
}
}
// Better using `let` than `var`
function guessnumber() {
let secret_number = Math.floor(Math.random() * 10) + 1;
let guess = askValue();
let attempts = 0; //initialse attempts with zero
let i = 0;
let resultMessage = "You won, you take ";
let win = false; //declare win
while (win == false) {
attempts++;
if (guess < secret_number) {
alert("The secret number is bigger");
i++;
guess = askValue();
} else if (guess > secret_number) {
//s lowercase not capital
alert("The secret number is smaller");
i++;
guess = askValue();
} else if (guess == secret_number) {
win = true;
resultMessage += attempts + " attempt" + (i != 1 ? "s" : "");
alert(resultMessage);
} else {
guess = askValue();
}
}
}
// call the function
guessnumber();

Javascript - Rock, Paper, scissors with switch statement? If not what are alternatives?

I am running the following codes bellow it only prints 'Draw!' the other cases does not work, what am I doing wrong?
const rps = (p1, p2) => {
var s = 'scissors';
var p = 'paper';
var r = 'rock';
var ans = '';
switch (rps) {
case (p1 == p && p2 == r):case (p1 == s && p2 == p): case (p1 == r && p2 == s):
ans = ('Player 1 won!');
break;
case (p1 == s && p2 == r): case (p1 == r && p2 == p): case (p1 == p && p2 == s):
ans = ('Player 2 won!');
break;
default: ans = ('Draw!');
break;
}
return ans
}
rps('paper','scissors')
switch compares the value you put in (rps which is a function) with each case (which will be true or false).
Since the function never matches a boolean, you always end up hitting the default case.
what am I doing wrong?
Trying to use switch for something it isn't really suited to.
Use if and else instead.
let rock = 2;
let scissors = 4;
let paper = 8;
let firstPlayerChoice = rock;
let secondPlayerChoice = paper;
switch (firstPlayerChoice / secondPlayerChoice) {
case 1:
console.log('there is a tie! pick again');
break;
case 0.5:
case 4:
console.log(`first player won!`);
break;
case 2:
case 0.25:
console.log(`second player won!`);
break;
default:
console.log('something went wrong!');
}
¡Hello!,
You are misunderstanding the use of "switch", the switch works like this:
The switch expression is evaluated once.
The value of the expression is compared with the values of each case.
If there is a match, the associated block of code is executed.
Soruce: https://www.w3schools.com/js/js_switch.asp
Like Quentin says, use "if" instead

Why does Math.floor(Math.random()) function always return "0"?

I am writing a program that chooses a random number between 0 and 1 and then enters a while loop until the random number generator selects a value more than .5. Every time I run the program, the program returns 0 and loops infinitely until it crashes. Why is this occurring? Shouldn't Math.floor(Math.random()) eventually select a number higher than .5?
var randomNumber = Math.floor(Math.random());
while(randomNumber < .5) {
var name = prompt("Do you want to play a game? Like checkers or something?");
if (name === "Yes") {
console.log("Good jorb!");
} else if(name === "No.") {
console.log("Go away!!!!!");
else {
console.log("I have no idea");
}
var randomNumber = Math.floor(Math.random());
}
This line almost always return 0 and that is why it does not get into the while.
var randomNumber = Math.floor(Math.random());
Math.random() return float values lower than 1 starting from 0 ... and with Math.floor you are getting the int part which indeed is 0
Your variable randomNumber was already initialized with your first line, to change it's value simply use randomNumber = newValue where newValue is the value you wish to set it to, using a method or hardcoded value. You do not need to use the var keyword again.
Also using Math.floor method on Math.random will always return 0, as Math.random will return a number between 0 and 1, which will floor to 0.
You were missing the closing bracket on your while loop.
I cleaned you code up a little to chain your if boolean operators, although there are better ways to construct this code.
var randomNumber = Math(Math.random());
while(randomNumber > .5) {
var name = prompt("Do you want to play a game? Like checkers or something?");
if (name === "Yes" || name === "yes" || name === "Yes." || name === "yes." || name === "Yup" || name === "Yup." || name === "yup." || name === "yup")
{
console.log("Good jorb!");
}
else if(name === "No." || name === "No" || name === "no" || name === "no." || name === "nope" || name === "nope." || name === "Nope" || name === "Nope.")
{
console.log("That's too bad.");
}
else
{
console.log("I don't know, man. I don't know");
}
randomNumber = Math(Math.random());
};// Close your while loop.
Your while loop will never run.
Math.random() returns a number n where 0 <= n <1
Math.floor(n) returns n rounded towards zero.
so your variable randomNumber will always equal zero.
you could also replace your if statements with an array of values to check.
Then look up the index of name in that array.
if the index is -1 it doesn't exist otherwise log "Good jorb!"
var randomNumber = Math.random();
while(randomNumber > .5) {
var name = prompt("Do you want to play a game? Like checkers or something?");
var yesArray = ["Yes", "yes", "Yes.", "yes.", "Yup", "Yup.", "yup.", "yup"];
if(yesArray.indexOf(name) == -1) {
console.log("I don't know, man. I don't know");
} else {
console.log("Good jorb!");
}
randomNumber = Math.random();
}
There are several reasons:
Math.floor(Math.random()), will always be zero so the loop will never start. Math.random() will give a number between 0 and 1 and you are flooring that one that means you are always rounding off down, which means zero.
If you want the while to stop, it is better to break; when the condition is right.
This code will work:
var randomNumber = Math.random();
while(randomNumber > .5) {
var name = prompt("Do you want to play a game? Like checkers or something?");
if (name === "Yes") {
console.log("Good jorb!"); break;
} else if(name === "Nope.") {
console.log("Okay that is fine.");
} else {
console.log("I don't know, man. I don't know");
}
randomNumber = Math.random();
}
But now it does not just depend on the answer whether the loop will continue but also on randomNumber.
Try this: (Sorry if I got any of the counts wrong on the long expletive... there were a lot of them...)
while(true){
var name=prompt("Do you want to play a game? Like checkers or something?");
if(name.search(/^[yY](es|up)\.?$/)!=-1){
console.log('Good jorb!');
}else if(name.search(/^[nN]o(pe)?\.?$/)!=-1){
console.log('F'+'U'.repeat(12)+'C'.repeat(13)+'K'.repeat(9)+' Y'+'O'.repeat(11)+'U'.repeat(18)+'!'.repeat(12));
}else{
console.log("I don't know, man. I don't know");
}
if(condition){
break;
}
}
Just to clarify about the regular expressions: They essentially look for the different forms of the word with capitalization or no and punctuation or no representing the full word (^ is the beginning of the string and $ is the end of the string). That should save you a lot of trouble.
Oh, and try to avoid while(true) for real development practices. for(var i=0;i<2e7;i++) or something similar is a better practice, but i figure if it's just for command line, that should be fine.

determining var type from prompt command and if else statement

I'm trying to write this exercise from a book:
Write a program to ask yourself, using prompt, what the value of 2 + 2
is. If the answer is "4", use alert to say something praising. If it
is "3" or "5", say "Almost!". In other cases, say something mean.
I made this attempt:
var input = "" || 'number'
prompt ("How many is 2+2 ?", input)
if (input = 4)
print ("Awesome !");
else if (input = 3 || input = 5)
print ("Close !");
else if (input = 'number'
print ("wrong number");
else if (input = 'random text')
print ("use numbers only!")
I know it is wrong. This is I intended to do:
I need to determine the type of var, not just the value. I need to make var either number or string (according to typeof). Why ? For prompt imput, because below else if condition, will be based on which type was inputted.
I know that exercise didn't asked it, but I want make it superior.
= is assignment. == is comparison.
To convert the string that prompt gives you to a number, use parseInt(input,10) - that said, JavaScript will typecast for you, so there's no real need here. You can even tell if the user entered something that isn't a number by testing isNaN(input) for your "use numbers only" result.
So something like this:
var input = parseInt(prompt("How much is 2 + 2?",""),10);
if( input == 4) alert("Awesome!");
else if( input == 3 || input == 5) alert("Almost!");
else if( input == 10) alert("No GLaDOS, we're working in Base 10 here.");
else if( input == 42) alert("That may be the answer to Life, the Universe and Everything, but it's still wrong.");
else if( isNaN(input)) alert("Use numbers only please!");
else alert("You are wrong!");
I'd personally suggest:
var guess = parseInt(prompt('What is 2 + 2?'), 10);
switch (guess) {
case 4:
console.log('Well done!');
break;
case 3:
case 5:
console.log('Almost!');
break;
default:
console.log('Seriously? No.');
break;
}
JS Fiddle demo.
Or, to be more functional about it:
function answerMath (sum) {
var actual = eval(sum),
guess = parseInt(prompt('What is ' + sum + '?'),10);
if (guess === actual) {
console.log('Well done!');
}
else if (guess + 1 === actual || guess - 1 === actual) {
console.log('Almost!');
}
else {
console.log('Seriously? No.');
}
}
answerMath ('2*3');
JS Fiddle demo.
Note that while eval() is the only means I could think of in this situation to evaluate the sum passed to the function as a string, I'm not entirely sure it's a good recommendation (albeit eval() has more bad press than it perhaps deserves, though it does present risks).
In most programming languages, = is assignment, and == tests for equality. So
a = 4 assigns the number 4 to the variable a. But a == 4 checks to see if a is equal to 4.
So for your code, you'd need:
var input = "" || 'number'
prompt ("How many is 2+2 ?", input)
if (input == 4)
print ("Awesome !");
else if (input == 3 || input == 5)
print ("Close !");
else if (input == 'number')
print ("wrong number");
else if (input == 'random text')
print ("use numbers only!")
I'm going to build on David Thomas's answer a little, because if you wanted to make it better, you could easily turn it into a little game.
var numa = Math.round(Math.random() * (100 - 1) + 1);
var numb = Math.round(Math.random() * (100 - 1) + 1);
var answer = numa + numb;
var guess = parseInt(prompt('What is ' + numa + ' + ' + numb + '?'), 10);
switch (guess) {
case answer:
alert('Well done!');
break;
case (answer - 1):
case (answer + 1):
alert('Almost!');
break;
default:
alert('Seriously? No.');
break;
}
Further things you could do would be to include a timer to see how long the user took to answer the question, and ask them if they way to play again when they get it right.
Here is a Fiddle: http://jsfiddle.net/6U6eN/

Does switch statement start comparing cases from the top in this example?

I found this example to make range work with switch statement:
function GetText(value)
{
var result;
switch (true)
{
case ((value >= 26) && (value <= 50)):
result = ">= 26.";
break;
case ((value >= 1) && (value <= 25)):
result = "Between 1 and 25.";
break;
case (value == 0):
result = "Equals Zero.";
break;
}
return result;
}
But if I modify the code and remove the second check for the value the example will still work:
function GetText(value)
{
var result;
switch (true)
{
case ((value >= 26)):
result = ">= 26 .";
break;
case ((value >= 1)):
result = "Between 1 and 25.";
break;
case (value == 0):
result = "Equals Zero.";
break;
}
return result;
}
So if I passed 29 even that I have two true cases the first one will be selected. My question is that how switch statement works in most of programming languages it will start comparing from the top or its only in this case (and is it good or bad to write it like that?).
switch statement checks for matches from top to bottom.
From MDN docs on switch statement:
If a match is found, the program executes the associated statements. If multiple cases match the provided value, the first case that matches is selected, even if the cases are not equal to each other.
I would do something like this (with if and else if chains):
function GetText(value) {
var result;
if (value == 0) {
result = "Equals Zero.";
} else if (value <= 25) {
result = "Between 1 and 25.";
} else if (value <= 50) {
result = "Between 26 and 50.";
}
return result;
}

Categories