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
Related
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>
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 watching a tutorial on how to make a Zork like game in JavaScript and jQuery. It has been working so far but when I try to change the location running the game with a direction command, I get undefined instead of the new room.
var currentRoom = "start" ;
function changeRoom(dir) {
if(rooms[currentRoom].directions[dir] !== undefined) {
currentRoom = rooms[currentRoom].directions[dir];
$('#game-text').append("<p>" + rooms[currentRoom].description + "</p>");
} else {
$('#game-text').append("<p> You cannot go that way </p>");
}
}
EDIT: This code comes after the code above
$(document).ready(function(){
$('#game-text').append("<p>" + rooms.start.description + "</p>");
$(document).keypress(function(key){
if(key.which === 13 && $('#user-input').is(':focus')){
var value = $('#user-input').val().toLowerCase();
switch(value) {
case "north":
changeRoom("north");
break;
case "south":
changeRoom("south");
break;
case "east":
changeRoom("east");
break;
case "west":
changeRoom("west");
break;
default:
alert("Invalid move!")
}
}
})
})
I think it has something to do with this portion of code. The message "you can not go that way" appears when it should; but I do not get the description of the room that I entered - only a message of undefined. Sorry if I'm being unclear, this is my fist attempt at making a game and I know very little about JavaScript.
EDIT: These are two of the "rooms".
var rooms = {
"start": {
"description": "It is a sunny day, perfect for a walk!\
While walking, you come across an intersection;\
you can go <b>North</b>, <b>South</b>, <b>East</b> or\
<b>West</b>, which way do you choose?",
"directions": {
"north": "deadend",
"west": "shortcut",
"east": "garden",
"south": "home"
}
"garden": {
"discription": "Ahh the right path, I see you choose the long\
way around which leads through a lovley garden",
"directions": {
"west": "start",
"east": "deadend"
}
},
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)
apologies for the basic question but I'm just starting to learn JS. I'm trying to build a blackjack game, and I started off in my .js file by creating a constructor function (for the cards) and then I defined one of the methods in that function. Here is the code in my .js file (I've not shown what's inside the actual cardToString function as it's about 70 lines long):
EDIT: Some people have asked I include the entire code, so here it is:
function Card(rank, suit) {
this.rank = rank;
this.suit = suit;
this.toString = cardToString;
this.createNode = cardCreateNode;
}
function cardToString() {
var rank;
var suit;
switch (this.rank) {
case "A" :
rank = "Ace";
break;
case "2" :
rank = "Two";
break;
case "3" :
rank = "Three";
break;
case "4" :
rank = "Four";
break;
case "5" :
rank = "Five";
break;
case "6" :
rank = "Six";
break;
case "7" :
rank = "Seven";
break;
case "8" :
rank = "Eight";
break;
case "9" :
rank = "Nine";
break;
case "10" :
rank = "Ten";
break;
case "J" :
rank = "Jack";
break;
case "Q" :
rank = "Queen";
break;
case "K" :
rank = "King";
break;
default :
rank = null;
break;
}
switch (this.suit) {
case "C" :
suit = "Clubs";
break;
case "D" :
suit = "Diamonds";
break;
case "H" :
suit = "Hearts";
break;
case "S" :
suit = "Spades";
break;
default :
suit = nill;
break;
}
if (rank == null || suit == null)
return "";
else
return rank + " of " suit;
}
$(document).ready(function() {
$("#deal").click(function() {
$("#hit").fadeOut('slow');
});
});
I'm completely confused, because when I put this into the .js file the jQuery doesn't work, however when I comment out everything but the jQuery it works fine. I'm sure it's something basic that I'm just not aware of, but I've searched for a while and can't find an answer. Basically, I have no idea why my first few bits of JS stop the jQuery from working.
EDIT: Someone asked me if I checked the console for errors, and sure enough I do get one:
Uncaught SyntaxError: Unexpected identifier
Next to this it said "jsjquery.js:4" and I think 4 refers to the line of code which was an empty line right at the beginning (I have some comments on the first few lines, then left a line before I starting coding). I removed empty line, now it says the error is on line 80, which is this piece of code:
return rank + " of " suit;
This error goes away when I comment out everything but the jQuery.
This might make everything clear to you guys, but I'm still lost!
Thanks.
EDIT: Ok final edit I promise, haha. For anyone who might come across this question looking for an answer: I made a couple of syntax mistakes, but the real problem was that I didn't define the method cardCreateNode. I didn't realise that not doing so would cause everything else to not run. Thank you to everyone who responded!
default :
suit = nill;
break;
unexpected identifier is syntax error. Obviously you mean null here, not nill.
Since you have a different error based on the update of your post I'll answer your latest issue being that you receive an error on this line:
return rank + " of " suit;
You are missing the concatenation on the other side of " of " so it should look like this:
return rank + " of " + suit;
Also in your switch statement you have this line:
default :
suit = nill;
break;
I think here you mean to set the value to null not nill which would look like this:
default :
suit = null;
break;