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
Related
I want to use a switch and individually target each English version of the website.
I tried using en/lang, but it does not work...
The variable populates a div with the string.
I could not use just the case 'en' since the English text is different for both SE and NO, so I need to target the English version of SE and NO individually.
switch (document.documentElement.lang) {
// ------------------------------ SE -----------------------------------
case 'en/se':
var heroTitle = 'This is an se english title';
break;
case 'se':
var heroTitle = 'This is a swedish title';
break;
// ------------------------------ NO -----------------------------------
case 'no/en':
var heroTitle = 'This is a no english title';
break;
case 'no':
var heroTitle = 'This is a no title';
break;
}
Look into i18next -- its by far the best way to do translations in JS.
https://www.i18next.com/
But to answer your question you'll want the full country code and lang. like en_US and en_SE I suppose. You can get the user's language with navigator.language
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.
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.
I have a js array like that:
let data = [{status:"stay",points:[1,2,3,4,5]}, {status:"move",points:[1,2,3,4,5]},{status:"stay",points:[1,2,3,4,5]}]
And I want to do some pattern match, here is my code:
switch (data){
case [{status:"move",_},{status:"stay",_},{status:"move",_}]:
console.log("successfully!")
}
And I don't care the points array, but in js the placeholder "_" not exist, actually I know other method to do this, but if we just use switch-case, can it be solved?
I am a newbie of js, anynoe knows how to do it?
If I understand what you're trying to do correctly, you might try reducing your array to a string, and then use that string in the switch statement. Something like this:
var actionString = ""
data.forEach(function(datum) {
actionString += datum.status + ' ';
});
// Remove extra space at the end
actionString.trim();
console.log(actionString); // "move stay move"
Then your switch statement would be:
switch(actionString) {
case "move stay move":
console.log('success!');
break;
case "stay move stay":
console.log('failure?');
break;
/* etc */
}
Try
switch (data.status){
case "stay":
case "move":
console.log("successfully!")
break;
}
Documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
i need to identify the data/text being submitted from <input> if it contains any of the following. youtube, vimeo,normal website, jpg/png, plain text
if a youtube link is found {
//do something
} else if a vimeo link is found {
//do something
} else if a normal website is found {
//do something
} else if a (jpg/png) is found {
//do something
} else just a text {
} //do something
as of the moment is my syntax. the youtube & vimeo regex format were taken from other posts. but im not sure how to create the proper regex for the others.
ive tried some regex generator but its so complicated to use
im also interested to know if this is the proper way of executing multiple conditional statement.
$(function() {
$(document).on('click','.submit', function () {
var data = $('#input').val();
var youtube = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/;
var vimeo = /^(http\:\/\/|https\:\/\/)?(www\.)?(vimeo\.com\/)([0-9]+)$/;
if (data.match(youtube)) {
alert("utube");
}
else if (data.match(vimeo)) {
alert("vimeo");
}
else if ...
});
});
There is a million different ways to do this.
The other regex you need are roughly bellow. Also it will save you a bit of a headache if you lowercase your data
var data = $("#input").val.toLowerCase();
Web url
/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+#)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+#)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%#.\w_]*)#?(?:[\w]*))?)/
PNG / JPG is at end of the string
/(png|jpg|jpeg)$/
Plain text i guese would be what ever is left
The most efficient way is also to use a switch statement not a big if else
like this http://www.w3schools.com/js/js_switch.asp
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
I would suggest using a switch statement when you have multiple regex conditions to check for:
var data = $('#input').val();
var youtube = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/;
var vimeo = /^(http\:\/\/|https\:\/\/)?(www\.)?(vimeo\.com\/)([0-9]+)$/;
var normalWebsite = /^(?:ftp|http|https):\/\/(?:[\w\.\-\+]+:{0,1}[\w\.\-\+]*#)?(?:[a-z0-9\-\.]+)(?::[0-9]+)?(?:\/|\/(?:[\w#!:\.\?\+=&%#!\-\/\(\)]+)|\?(?:[\w#!:\.\?\+=&%#!\-\/\(\)]+))?$/;
var image = /<img\s+src\s*=\s*(["'][^"']+["']|[^>]+)>/;
switch (true) {
case youtube.test(data):
alert('youtube');
break;
case vimeo.test(data):
alert('vimeo');
break;
case normalWebsite.test(data):
alert('normal website');
break;
case image.test(data):
alert('image');
break;
default:
// Here we are assuming anything that doesn't match the above is plain text.
// You will need an additional regex if you want to make sure this doesn't contain html or code.
alert('Plain text');
break;
}