JavaScript window.alert not working - javascript

I recently began learning JavaScript and decided to create a program to factor quadratic functions. The program itself is longer, and takes three users inputs (secondnum,firstnum,thirdnum) representing a,b,c in the standard form ax^2+bx+c. The program functions normally until this block of code.
function discriminant(secondnum,firstnum,thirdnum) {
var disc = Math.sqrt(Math.power(secondnum,2)-(4*firstnum*thirdnum));
return disc;
}
ans1 = ((-1*secondnum) + disc)/(2*firstnum);
ans2 = ((-1*secondnum) - disc)/(2*firstnum);
window.alert(ans1);
window.alert(ans2);
My intention of this code is creating a function which solves for the discriminant, then uses the discriminant in the quadratic formula. I believe there is something incorrect about the discriminant function. Is this the proper way to use user input in the function?
I hope this question is not too specific.
Also if it matters here is an example of how I collect user input for (secondnum)
var secondnum = prompt ("enter b");
while (isNaN(secondnum) || secondnum == "") {
var secondnum = prompt ("enter a different b");
}
Thank you in advance.

I am not 100% sure on the math, but syntactically I think you are trying to do something like this
function discriminant(secondnum,firstnum,thirdnum) {
var disc = Math.sqrt(Math.pow(secondnum,2)-(4*firstnum*thirdnum));
return disc;
}
ans1 = ((-1*secondnum) + discriminant(firstnum, secondnum, thirdnum))/(2*firstnum);
ans2 = ((-1*secondnum) - discriminant(firstnum, secondnum, thirdnum))/(2*firstnum);
window.alert(ans1);
window.alert(ans2);
which will at least get your alert boxes working provided firstnum, secondnum and thirdnum are declared before this block executes

Related

Trying to make a language translation app

I am trying to make a translation app that can translate a number between 1-30 from english to its german/french counterpart. I think I am somewhat on the right track, ive made the arrays with all the translations, but the problems I am having is I don't know how to correlate the number the user puts in via a prompt, to one of the values in the array, example:
User is prompted for number between 1-30, user is prompted for language French/German = Translation
This is what I am trying to do. Bellow is what I have so far, feel free to nit pick, but bear in mind I am new to Javascript so there is probably a lot wrong.
function translate() {
if (lang = "French") {
console.log(frenchTranslation);
} else {
console.log(germanTranslation);
}
};
var x=translate
translate(x)
var number=(Number(prompt ("What is your number? Must be between 1-30")));
var lang=(prompt ("What is your language? Must be 'French' or 'German'. Case Sensitive."));
var frenchTranslation = ["Please enter a number between 1-30", "un","deux","trois","quatre","cinq","six","sept","huit","neuf","dix","onze","douze","treize","quatorze","quinze","seize","dix-sept","dix-huit","dix-neuf",
"vingt","vingt et un","vingt-deux","vingt-trois","vingt-quatre","vingt-cinq","vingt-six","vingt-sept","vingt huit","vingt-neuf","trente"];
var germanTranslation = ["Please enter a number between 1-30","Eins","Zwei","Drei","Vier","Fünf","Sechs","Sieben","Acht","Neun","Zehn","Elf","Zwölf","Dreizehn","Vierzehn","Fünfzehn","Sechzehn","Siebzehn","Achtzehn","Neunzehn",
"Zwanzig","Einundzwanzig","Zweiundzwanzig","Dreiundzwanzig","Vierundzwanzig","Fünfundzwanzig","Sechsundzwanzig","Siebenundzwanzig","Achtundzwanzig","Neunundzwanzig","Dreiβig"];
Right, so first of all, you need to add some input validation to know what the user has selected. I recommend storing it somewhere, then you should make sure that it's in the correct range. Just use an if statement to check if the number is >= 0 && <= 30. After that when you're trying to use console.log you need to use array index of the correct number.
Here's my solution, you can improve on it a lot.
var frenchTranslation = ["Please enter a number between 1-30", "un","deux","trois","quatre","cinq","six","sept","huit","neuf","dix","onze","douze","treize","quatorze","quinze","seize","dix-sept","dix-huit","dix-neuf",
"vingt","vingt et un","vingt-deux","vingt-trois","vingt-quatre","vingt-cinq","vingt-six","vingt-sept","vingt huit","vingt-neuf","trente"];
var germanTranslation = ["Please enter a number between 1-30","Eins","Zwei","Drei","Vier","Fünf","Sechs","Sieben","Acht","Neun","Zehn","Elf","Zwölf","Dreizehn","Vierzehn","Fünfzehn","Sechzehn","Siebzehn","Achtzehn","Neunzehn",
"Zwanzig","Einundzwanzig","Zweiundzwanzig","Dreiundzwanzig","Vierundzwanzig","Fünfundzwanzig","Sechsundzwanzig","Siebenundzwanzig","Achtundzwanzig","Neunundzwanzig","Dreiβig"];
function translate()
{
const yournumber = Number(prompt("Enter your number (1-30)"));
console.log(yournumber);
const language = prompt("Choose a language - German or French");
if(yournumber < 1 || yournumber > 30) {
alert("Too hard");
}
else {
if(language === "French") {
console.log(frenchTranslation[yournumber]);
}
if(language === "German") {
console.log(germanTranslation[yournumber]);
}
}
}
translate();

Making a simple HTML calculator issue in Javascript

I am learning Javascript and I am trying to make a simple HTML calculator where 2 prompts appear asking for numbers to add. Anytime I execute I get just the 2 numbers added together like 2 + 2 = 22, I did something wrong because I would want the response to be the right answer. Thanks so much!
'use strict';
let txt = prompt('Please enter your calculation');
let cal = prompt('And the other one');
let orange = txt;
let apple = cal;
alert(orange + apple);
Your prompt inputs (txt and cal) are strings... you need to parse them to integers
let txt = prompt('Please enter your calculation');
let cal = prompt('And the other one');
let orange = parseInt(txt); let apple = parseInt(cal);
alert(orange + apple);
if you also want to add floats, use parseFloat() instead of parseInt()

How can I make this Google Apps Script loop efficiently?

I'm making an script that increases the value of a cell by 0.01 until it matches the value of another cell (gets the value, pass through a formula than see if the other cell value matches). The problem is that it takes too long to execute. It was very simple to do on excel, but I don't know how to program in G-Apps Script (neither js).
I guess it's taking too long because it runs on the cloud. There is anyway I can solve it?
Here the code so far:
function Calculate() {
var ss = SpreadsheetApp.getActive();
var vF = ss.getSheetByName('magic').getRange('C31').getValue();
ss.getSheetByName('magic').getRange('C32').setValue(0);
var vE = ss.getSheetByName('magic').getRange('C32').getValue();
var vP
for(vE=0;vE != vP;vE+=0.01){
ss.getSheetByName('magic').getRange('C32').setValue(vE);
var qParc = vF - vE;
ss.getSheetByName('magic').getRange('C3').setValue(qParc);
vP = ss.getSheetByName('magic').getRange('F3').getValue();
}
Thanks in advance!
More likely it's running "too long" because vE != vP is never false, because the kind of floating point used by JavaScript (IEEE-754 double-precision binary floating point, used by most programming languages) is inherently imprecise. Famously, 0.1 + 0.2 is not 0.3 (it's 0.30000000000000004). As a result, it's unreliable to use == or != (or === or !==) with possibly-fractional numbers. (You're okay if they're integers, provided they're not really big ones.)
There probably isn't any need for a loop if you want to update a value to make it match another. Just take the difference and add that to the one you're updating.
But if you do need the loop, replace != with <.
for (vE = 0; vE < vP; vE += 0.01) {
You're also repeating a lot of operations, perhaps expensive ones, there. Once you have the object for (say) a sheet or cell, remember that object reference and reuse it:
function Calculate() {
var ss = SpreadsheetApp.getActive();
var magic = ss.getSheetByName('magic');
var c32 = magic.getRange('C32');
var c3 = magic.getRange('C3');
var f3 = magic.getRange('F3');
var vF = magic.getRange('C31').getValue();
var vE, vP, qParc;
for (vE = 0; vE < vP; vE += 0.01) {
c32.setValue(vE);
qParc = vF - vE;
c3.setValue(qParc);
vP = f3.getValue();
}
}
(I also removed an unnecessary var vE = c32.getValue(); from that, since you immediately overwrite vE with 0 at the beginning of the loop. I just added the declaration to the var declaring vP and, now, qParc.)

Issue with passing property through function

First off my apologies if I did something incorrectly with asking a question, I'm very new to stackoverflow and javascript as well. I am having an issue with passing a property through my getPassword function and I've searched around and couldn't truly pinpoint an answer. The code I created is designed for an object called "student" with two properties; FirstName and LastName.
Using a couple of dialogue boxes the information related to each student is entered. At the end, a prompt should display and asks the user "Do you want to add more student?" If the answer is "Yes", It asks the next student's information. If the answer is anything else, It stops asking. Then the information is displayed on the webpage. I want to have a property called "UID" The format of UID is FirstName_PSWD. For calculating the "PSWD" the function called "generatePassword" is used. This function randomly creates a 6-digit password including characters and numbers. For example: if username is John, then UID may be "John_X12bn231". I can not seem to get this password function to work, what might I be doing wrong? I am also aware that there might be other errors in my code, which I do apologize for i am very much a beginner.
var student={FirstName:"", LastName:""};
var studentlist=[];
var i=0;
function generatePassword() {
var length = 4,
charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
retVal = "";
for (var i = 0, n = charset.length; i < length; ++i) {
retVal += charset.charAt(Math.floor(Math.random() * n));
}
return retVal;
}
function Register() {
var next="Yes";
while (next="Yes"){
student.FirstName=prompt("Please enter the name");
student.LastName=prompt("Please enter the last name");
studentlist.push(student);
document.getElementById("demo").innerHTML += "<li> <b>First Name:</b> "+ studentlist[i].FirstName + "," +
"<b>Last Name: </b>"+ studentlist[i].LastName + "," + "</li>";
next = prompt ("Do you want to add more data?", "Yes")
i++;
}
}
Two mistakes:
var student={FirstName:""; LastName:""};
Should be -> var student={FirstName:"", LastName:""};
var i==0; -> var i = 0;
Try after changes and tell me if it works ;d
Btw. Javascript is a frontend. Your users will be able to check how you generate the password, because all your code can be read.

New to javascript, how to assign an input value to a submit button?

I'm new to javascript and need help with a piece of my code. I am suppose to create a text box that a user can input a number and the function will then roll that many dice. I also need to set limits so a user can't enter -10 or 100 because it is only 1-6. So it looks like this:
var theInput = document.getElementById('num').value;
theInput = parseInt(theInput);
if (theInput < 1) {
theInput="1";
}
else if (theInput > 6) {
theInput = "6";
}
The part I'm stuck on is how I am suppose to link a text box to this piece of code that will then run through my function for dice rolling.
<script type="text/javascript">
function SelectImage6() {
document.getElementById('outputDiv').innerHTML ='';
for(i=0; i<6; i++){
roll2 = Math.floor(Math.random() * 6) + 1;
imgName2 = '../images/die' + roll2 + '.gif';
document.getElementById('outputDiv').innerHTML +=
'<img alt="die image" src="' + imgName2+'" />';
}
}
</script>
<body>
<div style="text-align:center">
<input type="button" value="Click to Roll" onclick="SelectImage6();">
<p id="outputDiv">
<img id="dieImg2" alt="die image"
src="../images/die2.gif" >
</p>
</div>
Where do I assign the var theInput within my code? Any help would be greatly appreciated. Thanks!
Well first you should create the textbox in the html like this:
<input type="text" id="num">
Then have people push a button to start your javascript code. So use the button you already have. Then when the SelectImage6() function is called on the button click, you just put the top javascript code (the one checking the input) into the function SelectImage6() and you will have a nice function that does it all.
To answer the specifics of your question, it makes most sense to get the number of dice to roll inside the SelectImage6 function. To make things nice and clean, you might want to encapsulate that functionality:
// returns the number of dice the user entered. if the user entered a non-numeric
// value, this function will throw an exception. if the user entered less than
// one, the value will be clamped to 1, and if the user entered more than six, the
// value will be clamped to 6.
function getNumDice() {
'use strict';
var numEntered = parseInt( document.getElementById('num').value );
if( isNaN( numEntered ) ) throw 'The number of dice must be numeric.';
if( numEntered < 1 ) numEntered = 1;
if( numEntered > 6 ) numEntered = 6;
return numEntered;
}
I cleaned up your function a little bit. "theInput" is a bit vague for a variable name, so I changed it to something more descriptive. I handled the case where the user doesn't enter a number, and I consolidated the document.getElementById and the parseInt into one line. Also, you were mixing types in your original code. You use parseInt (which returns a numeric type), but then you would set theInput to a string. This may not result in an error thanks to JavaScript's flexible type coercion, but it's bad practice regardless.
Now that you have that function, you can modify your SelectImage6 accordingly:
function SelectImage6() {
'use strict';
var div = document.getElementById('outputDiv'); // cached for efficiency
var html = '';
var roll2, imgName2;
var numDice = getNumDice();
for( i=0; i<numDice; i++ ){
roll2 = Math.floor(Math.random() * 6) + 1;
imgName2 = '../images/die' + roll2 + '.gif';
html += '<img alt="die image" src="' + imgName2+'" alt="die" />';
}
div.innerHtml = html;
}
For SelectImage6, I made some changes (in addition to using the value returned by getNumDice). First, you're repeatedly calling getElementById (once, unnecessarily, at the top of the function, then once for every dice rolled!). Any DOM access is expensive, and if you can avoid doing it multiple times, you should. Secondly, you're repeatedly modifying the innerHtml property which, depending on the complexity of your HTML, and your network latency, could cause flicker or other unpleasant effects. What I chose to do instead was to build up the string first, then set it all at once.
In your original function, you were unwittingly using global variables (implied globals) because you didn't declare roll2 and imgName2 as variables. I fixed that, and added use strict to your functions so this mistake will be caught in the future! (My advice is to always set use strict.);
I hope this helps! Welcome to the world of JavaScript.

Categories

Resources