I used if, else if, and else statements before and today I've decided to use switch statements which really simplified my code. My question is, just like if statements, is there a way I can add multiple conditions inside a switch statement?
Here's an example:
<script>
var textInput = input.value;
switch (textInput) {
case "orange":
text = "You decided to eat an orange. Do you want to eat another fruit?";
}
document.getElementById("message").innerHTML = text;
</script>
But say I wanted to add a response to the question I added about if you wanted to eat another fruit. How would I add another condition inside that case to where I could get a response back if someone types in yes or no to the question?
Is something like that possible? I hope my question is easy to understand.
Thanks for your help!
You can put any ordinary code inside the case, so you can add if statements:
switch (textInput) {
case "orange":
if (some_other_condition) {
text = "You decided to eat an orange. Do you want to eat another fruit?";
} else {
text = "OK, that's the last fruit";
}
break;
...
}
As long as you don't break the case, it will continue through the switch statement.
switch (textInput) {
case "orange":
text = "You decided to eat an orange. Do you want to eat another fruit?";
// break; we won't break here since it's commented out
case "fruit":
text = "You decided to eat a fruit?";
break;
}
will assign You decided to eat a fruit? to text if textInput is orange or fruit.
This gives you a limited ability to merge certain context, but it is a very bad practice to do so.
you can do something like this although in general it's not the way to go:
function test(input1, input2) {
switch (true) {
case input1 > input2:
console.log(input1 + " is larger than " + input2);
break;
case input1 < input2:
console.log(input2 + " is larger than " + input1);
break;
default:
console.log(input1 + " is equal to " + input2);
}
}
test(5,6);
Yes, you can put If conditions inside a switch, try it here.
switch (true) {
case (dog === 'pet' && cat === 'pet'):
// execute
break;
case (foo === 'bar'):
// do something else
break;
default:
// text = "You decided to eat an orange. Do you want to eat another fruit?";
}
Absolutely!! Adding to your code:
<script>
var textInput = input.value;
switch (textInput) {
case "orange":
text = "You decided to eat an orange. Do you want to eat another fruit?";
break;
case "banana":
text = "Had a banana today";
break;
case default: // Which cannot be found in the case will drop to here
text : ""; // DO nothing as per OP request
break;
}
document.getElementById("message").innerHTML = text;
</script>
For more details, please refer:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
Well, as far as I know you can't add conditions into switch statement. Switch statement just work to catch different states or 'cases' that one variable can take.
Maybe you can try with something like:
var addMore = true
while(addMore){
var textInput = prompt("Select your fruit");
switch (textInput) {
case "orange":
addMore = confirm("You decided to eat an orange. Do you want to eat another fruit?") // Maybe a yes or no question
default:
addMore = false
}
}
But if you have a UI you should use a multiple input component like Checkbox or something like that.
I hope it was helpful
You can insert the switch statement in a do-while loop, so the question loops until some predefined termination string is entered which will terminate the loop. This way you don't need multiple conditions inside each switch statement.
Check and run below:
var text = "Pick a fruit you'd like to eat: apple, orange, banana or none if you don't want any more";
var eaten = [];
do {
var textInput = prompt(text);
switch (textInput) {
case "orange":
eaten.push("orange");
text = "You decided to eat an orange. If you'd like to eat more type apple, orange, banana or none to end";
break;
case "apple":
eaten.push("apple");
text = "You decided to eat an apple. If you'd like to eat more type apple, orange, banana or none to end";
break;
case "banana":
eaten.push("banana");
text = "You decided to eat an banana. If you'd like to eat more type apple, orange, banana or none to end";
break;
default:
text = "The selection made was not valid\n\nPick a fruit you'd like to eat: apple, orange, banana or none if you don't want any more";
break;
}
} while(textInput !== "none");
var msgText = "You ate: ";
for(var i=0; i<eaten.length; i++) {
msgText += eaten[i];
if(i != eaten.length-1)
msgText += ", ";
}
document.getElementById("message").innerHTML = msgText;
<div id="message"></div>
Related
I'm in a bit of a pickle, regarding my Pseudocode for an assignment I'm working on. It was marked incorrect saying I need to add a validation loop (which I thought I did). I'm pretty new to coding as my background is in IT Support. Any help explaining to me how to add a loop validation into my Pseudo would be much appreciated as Pseudo isn't really taught in this course and I'm a bit lost to be honest.
//PSEUDOCODE FOR assignment1.js
//input
/*
ONCLICK.PROMPT
FUNCTION
WINDOW.PROMPT
VAR CHOICE("Which website would you like?")
WHILE true
SWITCH (CHOICE CASE 1 - 3)
BREAK;
ELSE alert ("please enter a valid number")
RETURN TO FUNCTION
*/
Actual JS Script (Linked to a HTML).
function pressButton(){
var myElement= document.getElementById("websites");
var choice = parseInt(prompt("Which website would you like?\n 1:Google \n 2:Yahoo \n 3:Bing \n","" ));
while (choice<0 || choice>3){
alert("please enter a valid number");
var choice = parseInt(prompt("Which website would you like?\n 1:Google \n 2:Yahoo \n 3:Bing \n","" ));
switch (choice) {
case 1:
window.open("https://www.google.com",'_blank', height=800, width=800);
break;
case 2:
window.open("https://au.yahoo.com","_blank", height=800, width=800);
break;
case 3:
window.open("https://bing.com","_blank", height=800, width=800);
break;
default:
text = "error: please choose from the options above";
}
}
}
The best way to follow pseudo-code is keep it with the real code. As for your issue, the loop performs the validation. Outside the loop (after it) is when a valid choice has been made. Currently your switch is inside the validation loop, which means it'll run when the choice value is invalid. This matches your pseudo-code but unfortunatley your pseudo-code is wrong. Its a tough balance keeping the pseudo code small enough to match how a computer steps through the calculation and keeping actual code out of the pseudo text. Here's how I'd change it.
// ONCLICK
// GET CHOICE
// WHILE CHOICE INVALID
// ALERT OF INVALID CHOICE
// GET CHOICE AGAIN
// OPEN CHOICE
// END FUNCTION
Other tips. Your switch doesn't need a default unless an invalid choice can be made. Your validation should not include 0. This is also a great scenario for do...while (although that alert becomes an awkward scenario).
// ONCLICK
function pressButton(){
var myElement= document.getElementById("websites");
// GET CHOICE
var choice = parseInt(prompt("Which website would you like?\n 1:Google \n 2:Yahoo \n 3:Bing \n","" ));
// VAR CHOICE("Which website would you like?")
// WHILE invalid
while (choice <= 0 || choice > 3) {
// ALERT OF INVALID CHOICE
alert("please enter a valid number");
// GET CHOICE AGAIN
var choice = parseInt(prompt("Which website would you like?\n 1:Google \n 2:Yahoo \n 3:Bing \n","" ));
}
// OPEN CHOICE
switch (choice) {
case 1:
window.open("https://www.google.com",'_blank', height=800, width=800);
break;
case 2:
window.open("https://au.yahoo.com","_blank", height=800, width=800);
break;
case 3:
window.open("https://bing.com","_blank", height=800, width=800);
break;
}
// END FUNCTION
}
You should not run the switch statement if the value of choice is beyond the range. There is a bug in your code which will print the message only once and then pass the incorrect values of choice to the switch statement.
function pressButton(){
var myElement= document.getElementById("websites");
var choice = parseInt(prompt("Which website would you like?\n 1:Google \n 2:Yahoo \n 3:Bing \n","" ));
while (choice<0 || choice>3) {
alert("please enter a valid number");
choice = parseInt(prompt("Which website would you like?\n 1:Google \n 2:Yahoo \n 3:Bing \n","" ));
}
switch (choice) {
case 1:
window.open("https://www.google.com",'_blank', height=800, width=800);
break;
case 2:
window.open("https://au.yahoo.com","_blank", height=800, width=800);
break;
case 3:
window.open("https://bing.com","_blank", height=800, width=800);
break;
}
}
The code above will keep asking the user to provide a number until user provides the right input. Also, you don't need the default case because the while loop will make sure that only the correct value is passed on to the switch block
I want to collect user’s scores from my GitHub page (theratcoder.github.io). I have used the following JS code (embedded in my HTML document) to create my quiz.
var score = 0;
var times33 = window.prompt("3 x 3");
switch(times33) {
case "9":
document.write("correct, ");
score++;
break;
default:
document.write("incorrect, ");
break;
}
var subtract5221 = window.prompt("52 - 21");
switch(subtract5221) {
case "31":
document.write("correct, ");
score++;
break;
default:
document.write("incorrect, ");
break;
}
var add56 = window.prompt("5 + 6");
switch(add56) {
case "11":
document.write("correct, ");
score++;
break;
default:
document.write("incorrect, ");
break;
}
var divide183 = window.prompt("18 / 3");
switch(divide183) {
case "6":
document.write("correct - ");
score++;
break;
default:
document.write("incorrect - ");
break;
}
var finishing_text;
switch(score) {
case 4:
finishing_text = "Great job!";
break;
case 3:
finishing_text = "Well done.";
break;
case 2:
finishing_text = "Better luck next time!";
break;
case 1:
finishing_text = "You need to work on your math!";
break;
default:
finishing_text = "You really need to work on your math!";
break;
}
var submit = window.confirm("Do you want to submit this quiz?");
var percent = score / 4 * 100;
if (submit) {
document.write("Your final score is " + score + " out of 4 (" + percent + "%). ");
document.write(finishing_text);
}
else {
location.reload();
}
I want to collect the values of the variable “score” so that I can get an idea of how people generally do on my quiz.
In order to do something like that, you'll need two things, a way to get the data to some form of storage, and the storage itself.
Unless some things have changed, github.io sites are static content only, so there's no server running in the background that you can access and communicate with your storage from, just your static content being served by the github.io service and running in the user's browser.
So the basic answer is you can't. But that's not true and there's always a hack if you're willing to do something gnarly. (I assume this is just for fun?)
If that's the case, you could run a server on your computer at home or something. Then when the user answers a question you add a call to the server on your computer at home and it takes that data and saves it and aggregates it however you want.
But end of the day if you want to store things about your users, you're probably going to want to have a dynamic website.
Although, maybe take a look at this if you're determined: https://medium.com/pan-labs/dynamic-web-apps-on-github-pages-for-free-ffac2b776d45 -- it's something like the "send data to your own computer" step, but using the free tier of firebase instead.
I'm a beginner trying to make a text adventure game in JavaScript, and I need to repeat a switch statement until the user enters a valid answer:
opts = prompt("Do you want to TALK or LOOK?").toUpperCase();
switch(opts) {
case "TALK":
mes = "Is anyone in charge here?";
speech = "Our leader is in the big building.";
talkNot();
break;
case "LOOK":
window.alert("The buildings are quite simple, and the doorways are much shorter than you. You notice, however, that there is a very tall, thin building at the end of the street.");
break;
default:
window.alert("That's not an option.");
}
Any answers would be super helpful - thanks!
Wrap the code with some function and callback the function in default statement
function run(){
opts = prompt("Do you want to TALK or LOOK?").toUpperCase();
switch(opts) {
case "TALK":
mes = "Is anyone in charge here?";
speech = "Our leader is in the big building.";
console.log('talk')
//talkNot();
break;
case "LOOK":
window.alert("The buildings are quite simple, and the doorways are much shorter than you. You notice, however, that there is a very tall, thin building at the end of the street.");
break;
default:
window.alert("That's not an option.");
run() //callback
}
}
run()
You can use a simple do ... while structure.
let next = false
do {
let opt = prompt("Do you want to TALK or LOOK?").toUpperCase();
next = false
switch (opt) {
case 'TALK':
case 'LOOK':
break;
default:
next = true
}
} while (next)
I have a problem with writing my code dynamic. I am doing a course in javascript programming and I am having some struggles with the final part of one assignment.
Exercise 8.2
Extend your switch-case statement with a default value. The result should
be 'That is an unknown fruit.' when the variable 'myFruit' has an unknown
value. Answer with the result where 'myFruit = pear'.
Write your code below and put the answer into the variable ANSWER.
var myFruit = "pear";
switch (myFruit) {
case "banana":
console.log("The banana is yellow.");
break;
case "apple":
console.log("The apple is green.");
break;
case "kiwi":
console.log("The kiwi is green.");
break;
case "plum":
console.log("The plum is purple");
break;
default:
console.log("That is an unknown fruit.");
break;}
How do I formulate this result in a variable?
I have tried to write like this:
var result = switch (myFruit);
But that does not work.
You can declare the result variable, and inside the switch statement cases, instead of console.logging the result, you can assign the value to the result variable, like so:
var myFruit = "pear";
var result;
switch (myFruit) {
case "banana":
result = "The banana is yellow.";
break;
case "apple":
result = "The apple is green.";
break;
case "kiwi":
result = "The kiwi is green.";
break;
case "plum":
result = "The plum is purple";
break;
default:
result = "That is an unknown fruit.";
break;
}
http://jsfiddle.net/uqxtmc25/
I won't write out all the code for you, but point you in the right direction. You need to set the text in a variable and return it:
switch ..
case "something":
var message = "Your message here.";
break;
...
Once your switch sets the value, then you use it as you need to.
You cannot return a value from a switch statement by using the switch statement like an operation.
You can not call the switch statement like var result = switch (myFruit);, it is not a function. You would have to move all the switch case code into a function:
function mySwitchCase(fruit){
var returnResult='';
switch (fruit) {
case "banana":
returnResult="The banana is yellow.";
break;
case "apple":
returnResult="The apple is green.";
break;
case "kiwi":
returnResult"The kiwi is green.";
break;
case "plum":
returnResult"The plum is purple";
break;
default:
returnResult"That is an unknown fruit.";
break;
}
return returnResult;
}
then you can call it like this:
var result = mySwitchCase(myFruit);
You can save the result in a variable answer and then use that variables to print out the result;
function fruitSwitcher (myFruit) {
var answer = "That is an unknown fruit.";
switch (myFruit) {
case "banana":
answer = "The banana is yellow.";
break;
case "apple":
answer = "The apple is green.";
break;
case "kiwi":
answer ="The kiwi is green.";
break;
case "plum":
answer = "The plum is purple";
break;
default:
// no really needed
answer ="That is an unknown fruit.";
break;
}
return answer;
}
var myFruit = "pear";
var answer = fruitSwitcher(myFruit);
console.log(answer); //That is an unknown fruit.
The default case in the previous code is superfluous as the variable answer is initialised to a default value. If an unknown fruit in passed in input, none of the switch cases matches it and, therefore, the answer variables never changes value and the function returns the default value.
There are five cases that are accepted. Still kind of a newbie to Java, so this is a slightly odd case. As far as I can tell (I've read the code at least twice) it should work perfectly fine, unless the double switch is making it not function... I get the error "SyntaxError: Unexpected token case"
var shouldWeapon = String("sword");
var user = prompt("There's a duck in a pond. It likes fish. What do you do? Would you like to feed it, kill it, skin it, buy it, or fight it").toLowerCase();
switch(user) {
case 'feed it':
var whatHaveFood = prompt("What do you have for food?").toLowerCase();
switch(whatHaveFood) {
case 'pancakes':
console.log("Great! Ducks love their pancakes!");
break;
case 'muffins':
console.log("I'm sorry what? You carry muffins? Ducks LOOOOOOOOOOOVE MUFFINS LIKE OMIGOSH I LOVE MUFFINS MMMM M M MMMM MMM IN MY TUMMY.");
break;
case 'dormant spiders':
console.log("You decide not to give them to the duck. They're yours. Nobody gets your dormant spiders.");
break;
case 'apple':
console.log("OH BOY I LOVE APPLES -said no duck ever.");
break;
default:
console.log("The Duck doesn't like that. He curses you to the pits of hell and walks away.");
break;
};
break;
case 'kill it':
var whatHaveWeapon = prompt("What sort of weapon do you have?").toLowerCase();
if(shouldWeapon || whatHaveWeapon){
console.log("Why Aren't you using a sword? Why are you using a " + String(whatHaveWeapon) + ". They Suck!");
}else{
console.log("Good choice. The Duck is vanquished.");
}
break;
case 'skin it':
var tempCat = prompt("What temperature is the cat?");
if(tempcat > 4){
console.log("Don't skin ducks.");
}
else{
console.log("That's a freaking cold cat.");
}
break;
case 'buy it':
var buyDuckCost = Math.floor(Math.random()*5 + 1);
var buyDucky = ("How much money do you have?");
var missingMoney = buyDuckCost - buyDucky;
if(buyDucky >= buyDuckCost){
console.log("You have bought a duck! congratulations!");
}
else{
console.log("I'm sorry you don't have that much money. You still need" + String(missingMoney) + "$! The duck pulls out a gun and shoots you.");
break;
case 'fight it':
var Smickle = true
var Donkey = false
if(Donkey || Smickle){
console.log("YOU CAN'T FIGHT THE DUCK. THE DUCK IS TOO STRONG");
}
else{
console.log("Ummmm... this is the only accessible answer..... OMEGA GOOD JOB*Cute anime loli voice.*")
}
break;
console.log("What? You're going to do what with the duck?")
default:
}
As far as I know, this should function....
In this part ("buy it" case), you are missing this end brace.
else {
console.log("I'm sorry you don't have that much money. You still need" + String(missingMoney) + "$! The duck pulls out a gun and shoots you.");
} //<<-- missing this end brace
break;
Code working here