How exactly are JS Case Switches supposed to be formatted? - javascript

So I have been working on a Discord bot for my server for a few days using Node.js and am brand new to JS. I am trying to convert some of the code from a Magic 8 Ball completed after a model for a tutorial to JS to Implement as a function (just the random number and case switch).
This is from the C# Project:
switch (random.Next(4))
{
case 0:
Console.WriteLine("YES");
speechSynthesizer.Speak("Yes");
break;
case 1:
Console.WriteLine("NO");
speechSynthesizer.Speak("No");
break;
case 2:
Console.WriteLine("HELL NO");
speechSynthesizer.Speak("Hell no");
break;
case 3:
speechSynthesizer.Speak("Hell yes");
Console.WriteLine("HELL YES");
break;
}
and this is in what I am trying to implement:
switch( Math.random.Next(4)) {
case 0:
msg.channel.send('Yes');
break;
case 1:
msg.channel.send('No');
break;
case 2:
msg.channel.send('Hell yes!');
break;
case 3:
msg.channel.send('Hell No!');
break;
}
I am essentially trying to add a part where you can send "Magic 8 Ball", and it will return a Yes/No/Hell Yes/Hell No.
Edit:
So I followed the advice of a comment, and switched "case" to all lowercase in each instance. The error I recieve now is that math is undefined. Another article just suggested switching math to Math. next is not a function.

If your problem is generating a random int to use in your switch, you'll need to know how to generate a pseudorandom int in the first place.
Math.random generates a a float in the range of [0, 1)
So you'll need to take that value, multiply it by your max, and then floor it to turn it in to an integer.
Math.floor(Math.random() * max)
Your final code would look like this:
switch(Math.floor(Math.random() * 4))) { // 4 is maximum n of options
case 0:
msg.channel.send('Yes');
break;
case 1:
msg.channel.send('No');
break;
case 2:
msg.channel.send('Hell yes!');
break;
case 3:
msg.channel.send('Hell No!');
break;
}

Related

How to display images using Switch statement?

I'm working on a Mass Effect personality quiz that has been adapted from the EasyDamus D&D quiz from the 90s, and I'm having trouble with the results page. Namely, I'm trying to include an image to match each result, but I don't know how to do so when the code implements the results using a switch statement. Here is a snippet of the code:
var win = window.open("", "win","width=900,height=550,top=25,left=50,toolbar=yes,menubar=yes,scrollbars=yes,resizable=yes,location=yes");
with (win.document) {
open("text/html", "replace");
write("<html><head><link rel='stylesheet' type='text/css' href='index.css'><title>Your Results Are In!\<\/title>\<\/head>");
write("<body text='#FFFFFF' font-family='massEffect' link='#5555FF' vlink='#6666EE' bgcolor='#F2ECDA' background='images/space.png'>");
write("<center><h2><b><font color='#FFFFFF'>You Are A:\<\/font>\<\/b>\<\/h2>\<\/center>");
write("<br><center><h1><b>");
switch (race) {
case "human": write("Human\<\/b> "); break;
case "asari": write("Asari\<\/b> "); break;
case "turian": write("Turian\<\/b> "); break;
case "salarian": write("Salarian\<\/b> "); break;
case "krogan": write("Krogan\<\/b> "); break;
case "quarian": write("Quarian\<\/b> "); break;
case "geth": write("Geth\<\/b> "); break;
case "volus": write("Volus\<\/b> "); break;
case "rachni": write("Rachni\<\/b> "); break;
case "batarian": write("Batarian\<\/b> "); }
switch (primclass) {
case "soldier": write(" Soldier"); break;
case "infiltrator": write(" Infiltrator"); break;
case "engineer": write(" Engineer"); break;
case "adept": write(" Adept"); break;
case "sentinel": write(" Sentinel"); break;
case "vanguard": write(" Vanguard"); }
switch (secclass) {
case "soldier": write("/Soldier"); break;
case "infiltrator": write("/infiltrator"); break;
case "engineer": write("/Engineer"); break;
case "adept": write("/Adept"); break;
case "sentinel": write("/Sentinel"); break;
case "none": write(""); break;
case "vanguard": write("/Vanguard"); }
write("<br><h2><br>Race:<br></h2>");
switch (race) {
case "human": `
The last line is the flavor text for each result, and while there's no issue with how it displays, I'm trying to find a way to have an image precede it. I have the pictures available, most of them in array called from a local folder. What would be the best way to have the images appear?
I've searched for solutions for a few weeks, most of which recommend event listeners, but I haven't been able to get it to work for me.
This code does a lot of stuff. First of all with switch statement, it should set up some variable for a particular case. Also its always a good practice to provide a default case for each switch-statement.
function decideOnRace(race) {
let result = '';
switch (race) {
case "human":
result = "Human\<\/b> ";
break;
default:
result = 'something else";
break;
}
}
// place this accordingly
const raceTextToWrite = decideOnRace(race);
write(raceTextToWrite);
Following this practice for all the different cases should help you progress e.g., for secclass, primclass, etc.

(Javascript prompt app ) switchcase inside switchcase will not run

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.

How to write my answer in a variable?

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.

Javascript switch not working with <option> tag values

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());

Jmeter Javascript Switch Statement Always Matches Default

I have been looking in both Jmeter and Javascript forums and can't figure out why this case statement is always matching to the default and I wondered if it was a Jmeter condition that I was missing.
I don't think it is a data problem. The URLTYPE_ variable is being set by a CSV input. Here are two lines from it.
Thumbnail,XXXXXX/XXXXXX,
Caption,XXXXXXXX/XXXXXX,
Code Snippet :
var t = vars.get("URLTYPE_");
log.info("starting");
log.info(t);
switch (t)
{
case "Thumbnail":
vars.put("CGIURL", "thumbres");
vars.put("LBURL", "thumb");
log.info("thumb");
break;
case "Caption":
vars.put("CGIURL", "capt");
vars.put("LBURL", "c");
log.info("c");
break;
default:
vars.put("CGIURL", "thumbres");
vars.put("LBURL", "thumb");
log.info("Default");
break;
}
log.info("stopping");
Try using if clauses instead of case with == comparison.

Categories

Resources