I am trying to create a calculator with javascript. - javascript

I can get the input from a user and i can put it all into a sum, but it retuns NaN.
my code:
var input1 = prompt("input 1","0");
var operation = prompt("operation","+");
var input2 = prompt("input 2","0");
var ans = (input1 + intput2);
if (operation = "+")
{
document.write("input1 + intput 2 = " + ans);
}
else
{
document.write("Other operations coming soon!");
}

There are couple of issues in this snippet.
You need to convert input1 & input2 if mathematical addition is expected. + sign before these variables are unary operator
There is a typo at intput2. In should me input2.
In the if condition validate using == or ===. operation = "+" is just assigning the value
var input1 = prompt("input 1", "0");
var operation = prompt("operation", "+");
var input2 = prompt("input 2", "0");
var ans = (+input1 + +input2);
if (operation == "+") {
document.write("input1 + intput 2 = " + ans);
} else {
document.write("Other operations coming soon!");
}

Prompt return the string so you need to convert the string to number using parseFloat() .And check the spell of input2 in var ans .
var input1 = prompt("input 1", "10");
var operation = prompt("operation", "+");
var input2 = prompt("input 2", "2");
var ans = parseFloat(input1) + parseFloat(input2);
if (operation = "+") {
document.write("input1 + intput 2 = " + ans);
} else {
document.write("Other operations coming soon!");
}

Related

“Syntax errors” appearing even though none seem to be present

I am writing a code that produces a random math quiz. However, when I run it (in an app called SoloLearn) it I get a Syntax error even though there doesn’t appear to be any. I even tested it in JSHint and no Syntax errors seemed to be present. Here is my code:
function random(max) {
return Math.floor(Math.random() * Math.floor(max));
}
function start() {
var form = document.getElementById("name_form");
var name = form.elements[0].value;
var score = 0;
alert("Let's begin!");
for (let i = 0; i < 4; i++) {
var num1 = random(10);
var num2 = random(10);
var operator = random(2);
if (operator == 0) {
var question = prompt(num1 + " + " + num2 + " =");
var answer = num1 + num2;
}
else {
var question = prompt(num1 + " - " + num2 = " =");
var answer = num1 - num2;
}
if (question == answer) {
alert("Correct!");
score++;
}
else {
alert("Incorrect ):");
}
}
document.write(score);
}
What is going on here?
In your line var question = prompt(num1 + " - " + num2 = " ="); you have misspelled a '+' which is a '=' in your code.
It should be:
var question = prompt(num1 + " - " + num2 + " =");
The same as #Nick Parsons said in the comments
Syntax error should be fixed by changing
var question = prompt(num1 + " - " + num2 = " =");
to
var question = prompt(num1 + " - " + num2 + " =");
which is the intent I believe

Need help understanding why I'm getting not-a-number output with computing imaginary Numbers

function ImaginaryNumbers(realNum, imaginary) {
this.realNum = 0;
this.imaginary = 0;
this.realNum = (typeof realNum === 'undefined') ? this.realNum : parseFloat(realNum);
this.imaginary = (typeof imaginary === 'undefined') ? this.imaginary : parseFloat(imaginary);
}
ImaginaryNumbers.transform = function(num) {
var imaginaryNumbers;
imaginaryNumbers = (num instanceof ImaginaryNumbers) ? num : imaginaryNumbers;
imaginaryNumbers = (typeof num === 'number') ? new ImaginaryNumbers(num, 0) : num;
return imaginaryNumbers;
};
function display_complex(re, im) {
if(im === '0') return '' + re;
if(re === 0) return '' + im + 'i';
if(im < 0) return '' + re + im + 'i';
return '' + re + '+' + im + 'i';
}
function addingComplexNumbers(first, second, third, fourth) {
var num1;
var num2;
num1 = ImaginaryNumbers.transform(document.getElementById("firstComplexNumber").value);
num2 = ImaginaryNumbers.transform(document.getElementById("secondComplexNumber").value);
num3 = ImaginaryNumbers.transform(document.getElementById("thirdComplexNumber").value);
num4 = ImaginaryNumbers.transform(document.getElementById("fourthComplexNumber").value);
var realNum = num1.realNum + num2.realNum + num3.realNum + num4.realNum;
var imaginary = num1.imaginary + num2.imaginary + num3.imaginary + num4.imaginary;
return document.getElementById("result8").innerHTML = display_complex(realNum, imaginary);
}
I try to get the users input but I keep getting NaN + NaNi as the following result. I'm not sure what the problem is. Any help would be appreciated.
You are not getting value from Input as number but as string so use parseInt to get an integer entered.
Current is:
num1 = ImaginaryNumbers.transform(document.getElementById("firstComplexNumber").value);
num2 = ImaginaryNumbers.transform(document.getElementById("secondComplexNumber").value);
num3 = ImaginaryNumbers.transform(document.getElementById("thirdComplexNumber").value);
num4 = ImaginaryNumbers.transform(document.getElementById("fourthComplexNumber").value);
Change to:
num1 = ImaginaryNumbers.transform(parseInt(document.getElementById("firstComplexNumber").value));
num2 = ImaginaryNumbers.transform(parseInt(document.getElementById("secondComplexNumber").value));
num3 = ImaginaryNumbers.transform(parseInt(document.getElementById("thirdComplexNumber").value));
num4 = ImaginaryNumbers.transform(parseInt(document.getElementById("fourthComplexNumber").value));

how to check if an input is a number in js

here is the code I've been working on.
var storeUsersInfo = [];
var amountOfUsers = prompt("How many users do you want?");
amountOfUsers = parseInt(amountOfUsers);
function returnUserInput() {
var askFirstName = prompt("What is your first name?");
var askLastName = prompt("What is your last name" + " " + titleCase(askFirstName) + "?");
var askAge = prompt("How old are you" + " " + titleCase(askFirstName) + " " + titleCase(askLastName) + "?");
if(askAge != int) {
alert("Not a valid input")
};
return {
firstName: titleCase(askFirstName),
lastName: titleCase(askLastName),
age: askAge
};
};
function titleCase(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
};
for(var i = 0; i < amountOfUsers; i++) {
storeUsersInfo[i] = returnUserInput();
}
console.log(storeUsersInfo);
I wondering how I can check the input of askAge to see if it equals a number.
I tried some code as you can see on lines 9-12 and I can't figure it out. I know it has to do something with typeof.
Thoughts?
multiply it by 1 and if it returns NaN and is not the same as the original input- its not a number
var askAge = prompt("How old are you" + " " + titleCase(askFirstName) + " " + titleCase(askLastName) + "?");
var askedAge=parseInt(askAge)*1;
if(askedAge != askAge) {
alert("Not a valid input");
}
This can be solved using a combination of Number.isInteger and Number.parseInt. Both of which have been standardized in ES2015.
The following expression will check if the age is valid:
Number.isInteger(Number.parseInt(askAge));
Note that you'll have to parse the user input to an integer first; this can either result in a valid integer or in NaN.
If it is an integer, then Number.isInteger will make the expression true; otherwise, the parsed number was NaN and the expression will become false.
I think you can you this code,
function isNumeric(x) {
return !isNaN(parseFloat(x)) && isFinite(x);
}
You could use
Number.isInteger(askAge)
Reference :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
try this
var check = /^[0-9]+$/;
var checkall = askAge.match(check);
if (!checkall){
alert("Not a valid input")
}
The cryptic answer:
var askAge = prompt("How old are you" + " " + titleCase(askFirstName) + " " + titleCase(askLastName) + "?");
if(!Number.isInteger(Number.parseInt(askAge))) {
alert("Not a valid input")
};
More:
You are partially correct in your assumption, you do have to check the type of the number to ensure that is is a number and also that it is an integer. How you actually DO that has several options. Here is one that should work.
You must determine if you wish to use Number() or Number.parseInt() as that determination will herein make a difference in the accepted values.
Given that, I choose to use the parseInt in this answer. I also constructed it to not accept 0 as a value for the number of users.
First we use or create the isInteger and parseInt in Number:
Number.isInteger = Number.isInteger || function(value) {
return typeof value === "number" && isFinite(value) && Math.floor(value) === value;
};
Number.parseInt = Number.parseInt || parseInt;
Declare our other functions: (commented)
// this will error out if "Cancel" on the prompt is clicked (null is passed in mystring)
function titleCase(mystring) {
return mystring.charAt(0).toUpperCase() + mystring.slice(1);
}
function returnUserInput() {
var isValid = false;
var askFirstName = "";
var askLastName = "";
var askAge = null;
do {
askFirstName = prompt("What is your first name?"); // currently accepts " " as a valid name
askLastName = prompt("What is your last name" + " " + titleCase(askFirstName) + "?"); // accepts " " as a valid name
askAge = prompt("How old are you" + " " + titleCase(askFirstName) + " " + titleCase(askLastName) + "?");
isValid = Number.isInteger(Number.parseInt(askAge));
if (!isValid) {
alert("Not a valid input");
}
} while (!isValid); // accepts 0 and negative values as age
return {
firstName: titleCase(askFirstName),
lastName: titleCase(askLastName),
age: Number.parseInt(askAge) // was using the unparsed string "4' if 4 was entered
};
}
Use the functions:
var storeUsersInfo = [];
var amountOfUsers = 0;
var enteredCount = 0;
do {
amountOfUsers = prompt("How many users do you want?");
enteredCount = Number.parseInt(amountOfUsers, 10);// parse it
} while (!(Number.isInteger(Number.parseInt(amountOfUsers, 10))) && !enteredCount > 0)
amountOfUsers = enteredCount;
for (var i = 0; i < amountOfUsers; i++) {
storeUsersInfo[i] = returnUserInput();
}
console.log(storeUsersInfo);// console.dir might also work (better?)

How to write a javaScript function to enter 2 numbers through prompts and display the sum of those numbers in an alert?

I wanted to display this:
Enter your numbers:
1st :
2nd :
Answer :
I tried doing this:
var a = prompt("A : ", "");
var b = prompt("B : ", "");
function calc(a,b)
{
return a + b;
}
alert ("The addition is =" + calc(a,b);
To do it with only one prompt:
var numbers = prompt("Enter two numbers separated by a semi-colon: ", "");
var a = numbers.split(";")[0];
var b = numbers.split(";")[1];
function calc(a,b)
{
return parseFloat(a) + parseFloat(b);
}
alert ("The addition of " + numbers + " is = " + calc(a,b));
You just need to parse the return from the prompts
var a = prompt("A : ", "");
var b = prompt("B : ", "");
function calc(a,b)
{
return parseFloat(a) + parseFloat(b);
}
alert ("The addition is =" + calc(a,b));

math array homework issue coding javascript?

this is what i have but i need to record the problems that are wrong and have the user answer them until there right, keep prompting the user for the problem until its right this was a 4 part problem and part3 is to have the same problem repeat until its completed
ex.(7+1=6) repeat(7+1=4) repeat (7+1=8) next problem
the user has to complete 5 problems and they have to be correct
<html>
<script>
var file=0;
var fileIndex=new Array();
var user=prompt("what is "+a+" + "+b);
var arr=[user,user,user,user,user];
var a=Math.floor(Math.random()*11);
var b=Math.floor(Math.random()*11);
var answer=parseInt(a+b);
var user=prompt("what is "+a+" + "+b);
while (user != answer && file++ != 4) {
fileIndex.push(user);
user = prompt("what is " + a + "+" + b);
} else {
alert("answer is:" + answer);
}
}//close for
</script>
Update:
var a = 1,
b = 1;
var answer = a + b,
tick = 0;
var file_index = [], copy;
function randomize() {
a = Math.floor(Math.random() * 11);
b = Math.floor(Math.random() * 11);
answer = a + b;
}
while (1)
{
if ((copy = prompt("What is " + a + " + " + " b?", 0)) != answer)
{
if (!copy) break;
file_index.push(copy);
randomize();
} else if (tick == 4) {
break;
} else {
++tick;
}
}
jsFiddle Demo

Categories