JavaScript For Loop with user entry error - javascript

I am currently dabbling with JavaScript and am doing some simple calculations using for loops and I am attempting to take user info for the Table set they want and the numbers they wish to multiply between e.g.
Enter Table set: 12
Enter where to start multiplying from: 3
Enter how high to multiply: 6
This would print:
12 x 3 = 36
12 x 4 = 48
12 x 5 = 60
12 x 6 = 72
My issue is that when I ask the user to select how high they wish to multiply to, if they select a number greater than 9 it doesn't enter the for loop and prints nothing yet 9 and below works.
This is the simple enough code:
function UserEnteredTables()
{
var tableNumber = prompt("Please enter the number tables to use: ");
var numberLowerLimit = prompt("Please select where you want to start multiplying from: ");
var numberUpperLimit = prompt("Please select how high to multiply to: ");
document.write("Before the loop " + numberUpperLimit + "<br/>");
for (i = numberLowerLimit; i <= numberUpperLimit; i++)
{
document.write("Made it inside the loop " + "<br/>");
document.write(tableNumber + " * " + i + " = " + (i * tableNumber) + "<br/>");
}
document.write("After the loop " + numberUpperLimit);
}
Apologies for any indentation issues, had issues pasting for some reason
I have attached two images, one where I enter the upper limit to 9 and then one were I enter 10. As you can see the 10 doesn't enter the loop.
I assume that I have missed something very simple but I would appreciate if someone could explain what the issue is or if its something to do with JavaScript loops.
If there is something wrong with the post or you require some other code to fully understand just let me know.
Thanks in advance :)

The issue is with the prompt value returned: its typeof is string, while what you want is number for the loop to work correctly.
Use parse() to extract the numeric value out of the prompt value, see here:
https://jsfiddle.net/jwvj2aab/1/
Note that you will need to handle user input in order to deny anything but numbers

Related

How can I get a true random from an array? Or should I do something else entirely?

I would like to display a different madlib each time a user clicks the submit button. Only needs to be clicked 3 times. I am using the functions below, but it doesn't seem all that random. I also have a snippet of the dogLib function that creates three madlibs and then calls the function above it to generate a random madlib string.
//Class: madlibGenerator.js
//----- Private Helper Functions -----
//Get Random: word strings for randam madlib
//Get Random: madlib string to display
function getRandomString(array) {
for(var i = array.length - 1; i>0; i--){
var j = Math.floor(Math.random() * (i+1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return this.word = array.pop();
}
//Set: set user input word string arrays into the getRandomString(array)
//Get: a final array of words to add to the madLib display strings
function getFinalWordArray(){
var prpN = getRandomString(this.properNouns);
var adjt = getRandomString(this.adjectives);
var noun = getRandomString(this.nouns);
var vrb = getRandomString(this.verbs);
return finalWordArray = [prpN, adjt, noun, vrb];
}
//Get Random Dog Lib
function getDogLib() {
//Get Random Dog Words
var dogWordsArray = getFinalWordArray();
//DogLibs
var dogLibOne =
"What is that " + dogWordsArray[1] +
" sound!" +
" Hey! " + dogWordsArray[0] +
"! You come " + dogWordsArray[3] +
" you crazy " + dogWordsArray[2] +
"!";
var dogLibTwo =
dogWordsArray[0] + "!! " +
dogWordsArray[0] + "!! " +
"Come " + dogWordsArray[3] +
" and lay on my clean " + dogWordsArray[2] +
" while your treat is still " + dogWordsArray[1] + "!";
var dogLibThree =
"My human comes home and takes me for a " + dogWordsArray[3] +
" where I sit on a " + dogWordsArray[2] +
" and get my " + dogWordsArray[1] +
" belly rubbed!";
//Make array of DogLibs
var dogLibArray = [dogLibOne, dogLibTwo, dogLibThree];
//Pick random dogLib string to display
finalDogLib = getRandomString(dogLibArray);
}
//Display: Random MadLib to console for now
function displayMadlib(pDisplayIDValue) {
if(pDisplayIDValue == "dogLib"){
//display
getDogLib();
console.log(finalDogLib);
}else if(pDisplayIDValue == "loveLib"){
//display
getLoveLib();
console.log(finalLoveLib);
}else if(pDisplayIDValue == "funnyLib"){
//display
getFunnyLib();
console.log(finalFunnyLib);
}
}
The code above isn't broken, it just doesn't produce a true random.
//Preferred Result: the program displays a different madlib each time the user clicks the submit button. The user only needs to click the button 3 times to get different madlibs, the fourth click clears the form and starts the program fresh.
Thank you!
I am open to any idea to make this a truly random madlibGenerator. Maybe counting number of clicks from a submit button?
So true randomness is going to be tough to achieve. Math.Random() from the javascript library isn't truly random as you've guessed, it's pseudo-random, meaning there is a pattern to it over a large number of inputs. Computers inherently can't really do true randomness, because they are always going to have to take some number, perform some sort of algorithm on it (these are usually "Mersenne Twisters" - fun wikipedia read), and spit out the result.
That said, I don't know exactly how to improve on what you've put into place here. With PRNG, a really large number of possible inputs can help a lot. If you want absolutely true randomness, the easiest way would probably be to hook into random.org's API (https://api.random.org/dashboard - developer license is free, limited to 1000 requests per day). Hooking into an API might be more work than you were planning on, but random.org uses (if I remember right) atmospheric noise and barometric pressure from the Earth to create their random numbers, so it's about as close to true randomness as you can possibly get.
I hope this helps!

How to write and call functions in javascript with for loops?

I am working on writing code for a course and need to figure out why the code output is not executing properly. I am very new to coding, this is a beginner assignment so all help and explanations are greatly appreciated.
The output should look like this:
Output:
How many times to repeat? 2
Stats Solver execution 1 ====================
give a number 10.10203
give a number 20
give a number 30
give a number 40
give a number 50
sum: 150.10203
average: 30.020406
max: 50
min: 10.10203
ratio: 4.94
Stats Solver execution 2 ====================
give a number 3.21
give a number 2.1
give a number 1
give a number 5.4321
give a number 4.321
sum: 16.0631
average: 3.21262
max: 5.4321
min: 1
ratio: 5.43
done ====================
Here is the code:
"use strict";
function myMain() {
var num = Number(prompt("give a number of times to repeat, must be 0 or greater"));
var count = num;
for (var a=0; a<=num; a++) {count++;}
alert("Stats Solver execution " + num + " ===================");
if (num===0){alert("done ==================="); return;}
wall()
alert("done ===================");
}
function wall(){
var num1 = Number(prompt("provide a number"));
var num2 = Number(prompt("provide a second number"));
var num3 = Number(prompt("provide a third number"));
var num4 = Number(prompt("provide a fourth number"));
var num5 = Number(prompt("provide a fifth number"));
var sum = (num1+num2+num3+num4+num5);
alert("sum: " + sum);
var avg = (sum/5);
alert("average: " + avg);
var max = (Math.max(num1,num2,num3,num4,num5));
alert("max: " + max);
var min = (Math.min(num1,num2,num3,num4,num5));
alert("min: " + min);
var ratio = (max/min);
alert("ratio: " + Math.floor(ratio*100)/100);
}
myMain();
Well you really aren't very far off at all. Actually your solution has all the code you need just some of it is in the wrong place. I would have posted this as a comment but as this is a new work account I can't actually post comments so here is a full solution with the explanations.
Your wall function, while annoying with all the alerts is actually correct and doesn't need any adjustments. With that said you might want to play with parseInt and parseFloat to make sure you are getting valid numbers but I am assuming that is outside of the scope of the assignment.
Now on to your main function.
var num = Number(prompt("give a number of times to repeat, must be 0 or greater"));
This is ok and will prompt the user for a number, once again you might want to test that you got a valid number using the aforementioned links.
var count = num;
for (var a=0; a<=num; a++) {count++;}
alert("Stats Solver execution " + num + " ===================");
if (num===0){alert("done ==================="); return;}
wall()
alert("done ===================");
This is where things start to fall apart a bit and where i think you are having problems. So I will break this down line for line and explain what each line is doing and you can compare that to what you think its doing.
var count = num;
Nothing crazy here, you are just creating another variable to hold the value in the num variable. Slightly redundant but not really a big deal.
for (var a=0; a<=num; a++) {count++;}
This is the line that appears to have given you the most confusion. This is the actual loop but inside the body of the loop { .... } nothing is being done except 1 is being added to count (count++). If I am understanding the assignment correctly, inside this loop is where you need to call your wall function after alerting the 'Stats Solver execution .....' stuff. All you need to do is move your function call inside this loop.
if (num===0){alert("done ==================="); return;}
wall()
alert("done ===================");
This part is clearly you a little lost and just trying things to get it to work, don't worry even after 12+ years of development i still write code like this ;). You really don't need this as the actual call to wall() will work fine for you.
I am bored and am waiting on work so for the sake of being a complete answer here is an example of how your code should look. Please don't just hand this in rather try and actually understand the difference between what i wrote and what you did because these are some very basic concepts that if you gloss over will make your life much harder down the road. Always feel free to ask, thats how people learn.
function myMain(){
// get the number of repetitions from the user and cast as a number
var num = Number(prompt('Please enter the number of times to repeat'));
// loop from 0 to the number the user provided - 1 hence the <
for (var i = 0; i < num; i++){
// alert the iteration of the loop, you will notice i add 1 to num when we alert it; this is because it starts at 0 so the first time it displays it would show 'Stats Solver execution 0 ======' instead of 'Stats Solver execution 1 ======'
alert('Stats Solver execution ' + (num + 1) + ' ===============');
// call your wall function
wall();
// go back to the top of the loop
}
// alert that we are done.
alert('done===============')
}
// your wall function goes here
// call your myMain function to kick everything off
myMain();
Just for fun you might want to look at console.log instead of alert to not make it such an annoying process with all the popups.
If i missed anything or you are confused about anything don't hesitate to ask and i'll do my best to answer.

Var won't exceed billion

EDIT
I tested something out, and apparently, this:
if(info.max.value == "") {maxdesiredvalue = 999999999999999999999}
Returns in the chrome console:
> maxdesiredvalue
< 999999999
So I believe the problem really comes from there... is there a maximum number of digits we can attribute to a variable?
I'm into javascript for a few months now, and I've made a program that generates random weapons for a tabletop rpg.
Every weapon generated has a price relative to it's attributes. My problem today is that this price won't exceed 9 digits (cannot reach billion), even though it can.
In my generator, it is possible to choose certain properties before generating the weapon. If I intentionally try to generate something worth over a billion gold, it will crash instantly. On the other hand, if there is any way the weapon can be generated without exceeding the billion, it will do so.
For example, the most expansive metal is the "Residuum". The only 2 weapons that can be generated in Residuum are the dart and the shuriken, since they only use 1/16 of an Ingot. Therefore if I set the metal to be Residuum, they will be the only 2 possible generated weapons. From this point, if I try to specify I want a Residuum Sword, it will simply crash as explained earlier.
In my generation options, I also have a text input for the user to choose a minimum value and/or a maximum value for the weapon. I set the default max value to Infinity, so it should'nt be a problem.
function desiredvalue(){
if(info.max.value == "") {maxdesiredvalue = Infinity}
else {maxdesiredvalue = parseInt(info.max.value)}
if(info.min.value == "") {mindesiredvalue = 0}
else {mindesiredvalue = parseInt(info.min.value)}
}
In my html:
Min price: <input type="text" name="min" value="" onchange="desiredvalue()">
Max price: <input type="text" name="max" value="" onchange="desiredvalue()">
I already tried to deactivate this function to see if it was the problem, but even without a specific max value, weapons still won't be generated if their value exceeds 9 digits.
Maybe the problem sets inside the value formula, so here it is, even though it might not be a big help since it is all made up from variables.
WeapValue = ((((IngotValue * Ingots) + CraftTime + (actualEnchantTime * 3) + (LS * 0.02) + (R * 0.05) + BS + (FTH * 0.03)) * (((BPArace + BPAstatus + BPAlevel + ((BPAcrit1 + 1) * BPAcrit2)) / 100) + 1)) + PAenchant + PAaugment1 + PAaugment2 + PAaugment3)
Also the value is modified afterwards to fit in gold, silver or copper...
WeapValue.toLocaleString('en-US', {minimumFractionDigits: 0});
WeapValue = WeapValue.toFixed(2);
if (WeapValue >= 2) {WeapValue2 = Math.ceil(WeapValue); goldtype = " GP"}
else if (WeapValue < 2 && WeapValue >= 1) {WeapValue2 = WeapValue * 10; goldtype = " SP"}
else if (WeapValue < 1 && WeapValue >= 0) {WeapValue2 = WeapValue * 100; goldtype = " CP"}
Nothing else in the script really change the value, and all the variables affecting it are defined earlier, and I don't really think they are the problem, since they actually seem to work (they simply make the price exceed 9 digits).
If you have any questions related to the script, I'm here to answer, but I can't put the full script since it is very, very long (2543 lines)...
If anyone has an idea of how I can deal with my problem, it would be so appreciated! Again, I'm not a javascript expert, but I did my best and looked a lot on the Internet for help, but I still can't get rid of this problem...
Thank you!

toFixed method doesn't work on user input but works on other vars in javascript, snippet included

I wanted feedback on why toFixed would not work in my JS alert when attached to the user input var usergb. Was a curious thing. I've been encouraged to post and I did not see any other questions out here regarding toFixed issues with user-input vars.
var downloadspeed = function () {
var usergb = prompt("How many gigabytes do you wish to download at 56 kilobits per second?");
console.log(usergb);
var hours = (usergb*8388608)/201600;
console.log(hours);
var days = (usergb*8388608)/4838400;
console.log(days);
//below in the alert is where you will see it, after the first concatenated string, I'd like to type usergb.toFixed(2) but it won't take.
alert("The number of hours it will take to download a " + usergb + " GB file at 56 kilobits per second is " + hours.toFixed(2) + " hours. This might be a big number. So, in terms of days to download, it'll take " + days.toFixed(2) + " days to download. This is why we have faster broadband speeds nowadays and why we have video streaming.");
}
downloadspeed();
The error I get is that it is not a function.
Grazie, Lou
toFixed is a method on a Number ...
prompt returns a String
try parseFloat(usergb).toFixed(2)
You have to use toFixed() on the number:
parseFloat(usergb).toFixed(2)
The prompt function returns a string, you can not use toFixed() on strings, only on numbers.
You need to cast the input as a number:
var usergb = +prompt("How many gigabytes do you wish to download at 56 kilobits per second?");
You can parse the input in the Number type. Example plunkr
var downloadspeed = function() {
var input = prompt("How many gigabytes do you wish to download at 56 kilobits per second?");
var usergb = new Number(input);
if(isNaN(usergb))
{
alert("You must input a number");
return;
}
console.log(usergb);
var hours = (usergb * 8388608) / 201600;
console.log(hours);
var days = (usergb * 8388608) / 4838400;
console.log(days);
//below in the alert is where you will see it, after the first concatenated string, I'd like to type usergb.toFixed(2) but it won't take.
alert("The number of hours it will take to download a " + usergb + " GB file at 56 kilobits per second is " + hours.toFixed(2) + " hours. This might be a big number. So, in terms of days to download, it'll take " + days.toFixed(2) + " days to download. This is why we have faster broadband speeds nowadays and why we have video streaming.");
}
downloadspeed();

Trouble with Loop and Functions in Javascript

So i have an assignment and ive been doing it now for a few hours and am very stuck on a few parts of it. So the parts im stuck on is having to use a loop to validate information put into a prompt, and using information from an array to coincide with with a variable in another function and finally displaying all of it.
So I have everything set up but have no idea what exactly im getting wrong here if someone would mind helping point me in the right direction? Oh I should probably mention Im trying to get the second function to go with the array so when the user enters a number (1 through 4) it matches with the prices in the array.
function numSeats() {
//var amountSeat=document.getElementById("price");
var amountSeat=prompt("Enter the amount of seats you would like");
amountSeat=parseInt(amountSeat);
for (i=7; i<amountSeat; i++){
if (amountSeat<1 || amountSeat>6) {
alert("Check the value of " + amountSeat);
location.reload(true);
}else{
alert("Thank You");}
}
return amountSeat;}
function seatingChoice() {
//var seatChoice=document.getElementById("table").innerHTML;
var seatChoice=prompt("Enter the seat location you want.");
seatChoice=parseInt(seatChoice);
for (i=7; i<seatChoice; i++){
if (seatChoice<1 || seatChoice>4) {
alert("Check what you entered for " + seatChoice);
location.reload(true);
}else{
alert("Thank You")}
}
return seatChoice;}
var price=new Array(60, 50, 40, 30);
var name=prompt("Please enter your name.");
if (name==null || name=="")
{
alert("You did not enter a name, try again");
location.reload(true);
}
else
{
alert("Thank You");
}
document.write(name + " ordered " + numSeats() + " for a total dollar amount of " + seatingChoice(
) );
It looks to me like you repeat the same error in both numSeats and seatingChoice;
Let's look at what you're doing with your loop
var amountSeat = prompt("Enter the amount of seats you would like");
for (i=7; i<amountSeat.length; i++) {/* amountSeat[i] */}
prompt asks the client for a String, so amountSeat is a String.
amountSeat.length is thus the number of characters in the String.
You start your loop at i = 7, thus amountSeat[i] starts from the 7th character in the amountSeat (assuming there are at least 7 characters in amountSeat)
It looks to me more like you want to get a number from the prompt;
// string
var amountSeat = prompt("Enter the amount of seats you would like");
// to number
amountSeat = parseInt(amountSeat, 10); // radix of 10 for base-10 input
Next, consider your if
if (amountSeat[i]<1 && amountSeat[i]>6) {
This is saying if less than 1 AND more than 6. No number can be both of these states at the same time, so it will always be false. It looks like you wanted to use an OR, ||
// do your check
if (amountSeat < 1 || amountSeat > 6) { /* .. */ }
Finally, it looks like you want to calculate the price by some logic, which you haven't included. However, I'm sure it will be based upon numSeats and seatingChoice so you will need to keep a reference to these choices.

Categories

Resources