I am making an app (idk what to call it) that shows up as a prompt and alert.
However, my code seems to unable to run a switchcase inside a switchcase which I use to add an order into a cart and also use to show the content of the cart.
Another way of saying what my problem is:
I cannot add items to my cart
I cannot access my cart (the prompt just closes itself)
To be more clear I will include my code below along with a codepen link of it and I will comment where I think the problems are.
All input is greatly appreciated.
Thanks!
arrayCart =[];
totalBill = parseInt(0);
cartContent = arrayCart.length;
for(;;)
{
userInput = parseInt(prompt('1. Menu\n2. Your Cart\n3. Payment\n4. Exit'))
switch(userInput)
{
// This is to go to Menu
case 1:
inputPesanan = prompt('Silahkan pilih menu yang diinginkan:\n1. Paket Bento A\n2. Paket Bento B\n3. Paket Bento C')
// I think the 1st problem starts here
switch(inputPesanan)
{
case 1:
arrayCart.push('Paket Bento A - Rp20.000\n');
totalBill += parseInt(20000);
break;
case 2:
arrayCart.push('Paket Bento B - Rp25.000\n');
totalBill += parseInt(25000);
break;
case 3:
arrayCart.push('Paket Bento C - Rp30.000\n');
totalBill += parseInt(30000);
break;
}
break;
// and the 1st problem ends here
// This is to check the Cart's content
case 2:
// And I think the 2nd problem starts here
inputKeranjang = alert('Isi Keranjang Anda\n' + arrayCart + '\n\n' + 'Total Tagihan Anda: \n' + totalBIll)
break;
// and it ends here
//----------- everything under this line seems to be working fine ---------------------------------------
// This is to input how much money you would like to pay with and calculate the change or deficit (if any)
case 3:
inputPayment = parseInt(prompt('Total Tagihan Anda :\nRp' + totalBill + '\n\nBerapa uang yang Anda akan bayarkan?'));
switch(true)
{
case inputPayment<totalBill:
alert('Uang Anda kurang sebesar Rp ' + parseInt(totalBill-inputPayment));
break;
case inputPayment>totalBill:
alert('Anda akan mendapat kembalian sebesar Rp' + parseInt(inputPayment-totalBill));
break;
case inputPayment=totalBill:
alert('Uang Anda pas');
break;
}
break;
}
// This is to end the infinite loop and close the app
if(userInput === 4)
{
break;
}
}
I'm not the javascript developer but as far switch statement goes,
This is how it works:
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.
So whatever you pass as input to the switch("YouInput") it checks for that in all cases, so If you pass Int as your Input in first switch, let say 1 then case 1: will execute if you pass 100 case 100: if no case match default will and if you pass String let say "Yosia" then if there is any case "Yosia": that will execute
So in your second switch cases you are checking for case 1: , case:2 but I don't think your "inputPesanan" is of type int beacuse in everywhere else you are using some parseIn but not there so may be print and check you "inputPesanan" it will not be 1, 2, or cases you are looking for.
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 wish to use case within a switch switch statement like so:
case 'transfer' + amount:
sql.get(`SELECT * FROM scores WHERE userId ="${userID}"`).then(row => {
sql.run(`UPDATE scores SET points = ${row.points - amount} WHERE userId = ${userID}`);
bot.sendMessage({
to:channelID,
message: `You have transferred ` + amount + ` points. You currently have ${row.points} points.`
})
break;
If it sees transfer10 I want the code to take that value 10 to be amount however I have no idea how to do that.
Thanks in advance :)
I do not think you can create switch statement with dynamic-generated case statements. I also do not see any real advantage of doing this, plus the logic behind this it would be hard to understand from anyone else who will be reading the code.
What about using the switch statement do determine the art of action and accessing the _amount_in the case statements ?
var amount, action;
// some code
...
amount = 2;
// some code
...
action = 'transfer' // or delete, update ...
// some code
...
switch(action) {
case 'transfer':
// do some SQL and access the amount
...
break;
case 'delete':
// do some SQL and access the amount
break;
default:
// some default action
}
If you really need something like a dynamically-created switch-statement look at the first answer from this question.
What I'm attempting to do is to create a switch statement that takes data from the JSON API and prints it depending on the location of the user.
For example, if the user is located in the US, then it prints only the city and state. If located outside of the US, it prints the city and the country. If the city is an empty string, then it prints only the country.
As of now, no matter what location I set my VPN to, it goes to the default case(city and country).
var location;
var city;
var state;
var country;
$.getJSON("http://ipinfo.io", function(data) {
console.log(data);
location = data.loc;
city = data.city;
state = data.region;
country = data.country;
switch (data) {
case country === 'US':
$("#yourCity").html(city + ", " + state);
break;
case city === "":
$("#yourCity").html(country);
break;
default:
$("#yourCity").html(city + ", " + country);
}
I chose to use a switch statement rather than an if statement because I may want to add more cases later on down the line.
Any help would be greatly appreciated.
You need to pass something more specific than just data in your switch statement. Since data is an object and not country or city it goes straight to the default.
I think you are thinking that when it goes through the case it looks through the object and sees if it has the value country or city, but it doesn't. You need to pass something like switch(data.location) and then data.location value is either country or city. So you might need to move things around a bit. Hope that makes sense!
Switch-case statement can be used only to compare one value with several others. According to your code sample, you have tried compare both country and city using switch case. That is not possible, definitely you'll have to use if-else statement handle this.
Please consider following method.
var location;
var city;
var state;
var country;
$.getJSON("http://ipinfo.io", function(data) {
console.log(data);
location = data.loc;
city = data.city;
state = data.region;
country = data.country;
if(country === 'US'){
$("#yourCity").html(city + ", " + state);
}else{
if(city===''){
$("#yourCity").html(country);
}else{
$("#yourCity").html(city + ", " + country);
}
}
You also used switch case statement in a wrong way. Switch case statements doesn't have arithmetic compare symbols. Try switch case statement as follows.
var day = new Date().getDay();
switch (day) {
case 4:
case 5:
text = "Soon it is Weekend";
break;
case 0:
case 6:
text = "It is Weekend";
break;
default:
text = "Looking forward to the Weekend";
}
You're not using the switch case properly.
Basically, you need to pass a specific type of data. Currently, the switch variable is not a country nor a city hence it goes straight to the default.
further reading:
JavaScript Switch Statement
I have the following HTML:
<select id="rankBox">
<option value="0">100</option>
<option value="1">150</option>
<option value="2">200</option>
<option value="3">250</option>
<option value="4">300</option>
<option value="5">350</option>
<option value="6">400</option>
</select>
<input type="Submit" id="button1" value="Generate" onclick="doStuff()">
and the following Javascript:
function doStuff() {
var choice = $("#rankBox option:selected").val();
console.log(choice);
switch (choice) {
case 0:
case 1:
colorQ = "^7";
break;
case 2:
colorQ = "^L";
break;
case 3:
colorQ = "^A";
break;
case 4:
colorQ = "^8";
break;
case 5:
colorQ = "^+";
break;
case 6:
colorQ = "^<";
break;
default:
alert("Something went wrong");
break;
}
alert(colorQ);
}
In short, I have a switch statement which is supposed to check the value of the option the user has selected. As you may see, I have added console.log to see if the problem is with acquiring the user's input, but that is not the issue. The issue is the switch statement, which just does not work.
Am I using wrong syntax or something?
jsFiddle: http://jsfiddle.net/3qTHW/2/ (jsFiddle doesn't work in my browser at all, says doStuff() is not defined)
Thanks in advance.
It's not an integer, it's a string, as all values from an element are strings.
You'll have to either parse it as an integer :
function doStuff() {
var choice = parseInt( $("#rankBox option:selected").val(), 10);
....etc
or change the switch to work with strings (you should be trimming)
switch ( $.trim(choice) ) {
case '0':
case '1':
....etc
This was an easy problem, by looking at the code one could see that the line var choice = $("#rankBox option:selected").val(); is adding string to variable choice. And that is the reason none of the case statements worked and the default code executed.
The best way not to run into such problems is to "Debug" your JavaScript code properly. This will save you a lot of precious time and you will find the root cause to each problem yourself.
To debug your code, you can use Firebug extension in Firefox. This will actually stop the code execution for you and guide you line by line telling you the state of each variable at every line of code. So in case of your problem, all I did was add your code in .html file and ran it in Firefox with "Debugger" points specified. The JS code looked like this.
function doStuff() {
var choice = $("#rankBox option:selected").val();
debugger; // This is the point where the debugging starts
console.log(choice); // console.log wont help as it did not tell me the type
switch (choice) { // Here Firebug tells me that choice is actually a string
case 0:
case 1:
colorQ = "^7";
break;
case 2:
colorQ = "^L";
break;
case 3:
colorQ = "^A";
break;
case 4:
colorQ = "^8";
break;
case 5:
colorQ = "^+";
break;
case 6:
colorQ = "^<";
break;
default:
alert("Something went wrong");
break;
}
alert(colorQ);
}
Note I put a "debugger" above console.log(). From this point onward, the code stopped at each line and I could see the value in each variable. This helped me notice string value in choice.
Happy Debugging :)
Use javascript parseInt() method like this :
var choice = parseInt($("#rankBox option:selected").val());