Adding two numbers together, get 5+10 = 510 instead of 15 - javascript

I just started learning JavaScript and I'm fiddling around with some code and I can't seem to find a way to really add two variables up and calculate their sum. I'm declaring 3 variables where I set one variable to the answer and the 2 others as the two numbers. So basically a, b, c where c = (a + b). However, whenever I try to run the code the result ends up in 'ab' instead of 'a + b' so if a = 5 and b = 10 it says '510' instead of '15'.
All the other symbols like '-' , '/' and '*' are working as intended, the only one that is not working is the '+'.
I figure the computer thinks I'm trying to print out the two strings but I want to add them up instead, just like you do when you alert something for example: alert("Hello World" + a);
Am I thinking in the right direction or is the problem something else? Here's the source code:
function addTwoNumbers(firstNumber,secondNumber,numberAdded){
if(numberAdded == '+'){
numberAdded = (firstNumber + secondNumber);
alert("The summ of the two numbers is equal to: " + numberAdded);
}
else if(numberAdded == '-'){
numberAdded = (firstNumber - secondNumber);
alert("The difference of the two numbers is equal to: " + numberAdded);
}
else if(numberAdded == '/')
{
numberAdded = (firstNumber / secondNumber);
alert("The 'kvot' of the two numbers is equal to: " + numberAdded);
}
else if(numberAdded == '*'){
numberAdded = (firstNumber * secondNumber);
alert("The product of the two numbers is equal to: " + numberAdded);
}
else
{
alert("I told you to use '+, -, / and *' not anything else!");
}
}
var checker = true;
while(checker == true){
alert("You will now be prompted to enter two numbers.");
var firstNumber = prompt("Please enter the first number.");
var secondNumber = prompt("Please enter the second number.");
var numberAdded = prompt("Would you like to use '+, -, /, or * ?'");
checker = false;
addTwoNumbers(firstNumber, secondNumber, numberAdded);
if(numberAdded != '+' && numberAdded != '-' && numberAdded != '/' && numberAdded != '*'){
checker = true;
}
option = 0;
while(option != 'y' && option != 'n'){
var option = prompt("Would you like to make a calculation again? (y/n)");
if(option == 'y'){
checker = true;
}
else if(option == 'n'){
checker = false;
}
else{
alert("I said (y/n), try again...");
}
}
}

The prompt function return a string. So when you use the + operator on two string you are combining them together. Instead, parse the number strings to a number:
var firstNumber = parseInt(prompt("Please enter the first number."), 10);
var secondNumber = parseInt(prompt("Please enter the second number."), 10);

Related

While loop exits instead of returning to the loop -Javascript

Trying to get only a number answer. The inner while loops exits instead of returning back into the loop. I'm not sure why.
var numPlays = prompt("How many games do you want to play?");
if (isNaN(numPlays) == true) {
while (isNaN(numPlays) == true) {
numPlays = prompt("That's not a number. Please pick a number.");
}
} else if (numPlays == 0) {
while (numPlays == 0) {
numPlays = prompt("You have to at least play one game. Please pick a number.");
}
} else if (numPlays == 1) {
alert("OK! Let's play " + numPlays + " game!");
} else {
alert("OK! Let's play best of " + numPlays + "!");
}
There is no need to ever enter a loop.
A quick example
// Wrap in a function so we can start over
function start() {
var numPlays = prompt("How many games do you want to play?");
// edited this to check for 0
if (isNaN(numPlays) || numPlays == 0) {
alert('Nope, bad answer, try again!');
return start();
} else if (numPlays == 1) {
alert('Ok, lets play 1 game!');
} else {
alert('Ok, lets play the best of ' + numPlays + 'games!');
// A little aside
// var neededToWin = (Math.floor((numPlays / 2)) + 1);
// alert('Ok, you need to win ' + neededToWin + ' out of ' + numPlays + ' games to beat me!');
}
}
Technically you would want the best out of 'half of the games + 1'.
So to win, you need to win 7/12 games. You could just find this out by dividing
Because of the if/elseif structure; only one of them can match. The first time it runs through, it asks for the number at line 1, then decides which branch of the if/elseif/else structure to go through. It doesn't matter that you're changing the value of numPlays later, the decision was already made!
You probably want a recursive call in here.
function getNumPlays(message) {
if (!message) { message = "How many games do you want to play?"; }
var numPlays = parseInt(prompt(message), 10);
if (isNaN(numPlays)) {
return getNumPlays("That's not a number.");
} else if (numPlays < 1) {
return getNumPlays("You have to at least play one game.");
}
return numPlays;
}
var numChosen = getNumPlays();
if (numPlays === 1) {
alert("OK! Lets play " + numChosen + " game!");
} else {
alert("OK! Let's play best of " + numChosen + "!");
}
PS: note the parseInt(..., 10) in there. This converts to either a number, or NaN. The '10' part is important; it specifies what base the number is in. Octal numbers are written "011", and sometimes the javascript engine won't know if you want octal or decimal.
An empty input would evaluate to false ('ok' in your while loop).
Try using parseInt(), which returns NaN for empty strings and non-numbers, Test a few of your own examples using this:
isNaN(parseInt(prompt("enter number")))
var numPlays = prompt("How many games do you want to play?");
while (isNaN(numPlays) == true || numPlays == 0) {
if(isNaN(numPlays) == true)
numPlays = prompt("That's not a number. Please pick a number.");
else
numPlays = prompt("You have to at least play one game. Please pick a number.");
}
if (numPlays == 1)
alert("OK! Let's play " + numPlays + " game!");
else
alert("OK! Let's play best of " + numPlays + "!");
Do we have to have all those nested loops... is that a requirement? can we make it simpler?

How to ask a user to guess a number between 1 - 1000

I'm trying to write some javascript code that asks the user to guess a number from 1 to 1000 and enter it into the prompt box. If the user guesses right, an alert box will pop up saying they got it right. If they guess wrong, another alert box will popup and say that they are wrong and to try once more.
The issue here is that I don't know what I have to do to make the code loop infinitely until they get the right answer. Here's what i have so far:
var a = 489; // the number that needs to be guessed to win the game.
//var b stores whatever value the user enters.
var b = prompt("Enter a number in between 1 and 1000");
// if/else statement that test if the variables are equal.
if (b == a) {
alert("You're right!");
} else {
alert("Incorrect! Try again!");
}
Number matching
Basically, when you make prompt, it returns a String or text, not a number. To fix this, do:
if (parseInt(b,10) === a) {
//Code
}
Other ways
They're a lot of ways to parse numbers. Here's a few more:
parseFloat(b); // Also parses decimals: '5.3' -> 5.3
parseInt(b, 10); // Gives an integer (base 10): '5.3' -> 5
+b; // A very 'short' way; '5.4' -> 5.4
Number('5.4e2'); // Number case: '5.4e2' -> 540
Looping
Now to repeat? Make it a loop!
var a = 432;
while (true) {
var b = prompt("Enter a number in between 1 and 1000");
if (b == a){
alert("You're right!");
break; // Stops loop
} else if (!b) { break; }
else {
alert("Incorrect! Try again!");
}
}
Not sure why, but some people hate while true loops. They shouldn't cause any problems as long as you coded it properly
Random Numbers
You can get a random number using Math.random.
var min = 1,
max = 1000;
Math.floor(Math.random() * (max - min + 1)) + min;
If you're like me and want short code, you can shorten it by:
Math.floor(Math.random() * (999)) + 1;
All Together Now!
var a = Math.floor(Math.random() * (999)) + 1;
while (true) {
var b = prompt("Enter a number in between 1 and 1000");
if (b == a) {
alert("You're right!");
break; // Stops loop
} else if (!b) {
alert("The Correct Answer was: " + a); //Shows correct answer
break;
} else {
alert("Incorrect! Try again!");
}
}
Just stick your prompt in some kind of loop. The code will inside the loop will run over and over until the comparison is false.
Basic example:
http://jsfiddle.net/s2he1twj/
var a = 500,
b;
while (parseInt(b) !== a) {
b = prompt('Enter a number!');
if (b === null) break;
}
while loop
Do this recursively by calling the same function like
var a = 489;
function promptGuess(){
//var b stores whatever value the user enters.
var b = prompt("Enter a number in between 1 and 1000");
// if/else statement that test if the variables are equal.
if (b == a){
alert("You're right!");
} else {
alert("Incorrect! Try again!");
promptGuess();
}
}
promptGuess();
Use a while until the match:
var a = 489;
var b;
while(b != a) {
var b = prompt("Enter a number in between 1 and 1000");
if (b == a) {
alert("You're right!");
} else {
alert("Incorrect! Try again!");
}
}
One more thing: although the b != a evaluation is correct, it's error-prone. The != operator do conversion type, whilst the !== operator compares types and value.
In your case: 5 != '5' will return false, but 5 !== '5' returns true. It's recommended that your comparisons be conversion-free. It's more strict.
In your case, this means:
while(parseInt(b) !== a)
Greetings!

If statement is null how do we return or carry onto other code to be input

var rateOfPay = Number(prompt("Enter your hourly rate of pay", " "));
var workHours = Number(prompt("Enter hours worked", " "));
if (rateOfPay === " " || rateOfPay === null);
{
alert("Please enter your Hourly rate \in Dollars");
console.log(rateOfPay);
}
else
{
}
I'm trying to setup this calculation so that it will ask the user for 2 var to be entered:
rateOfPay
hoursWroked
I want to check for null inputs or 0 and prompt user to re enter those variables if == null or 0. How would I go about setting this up?
this is the code that was accomplished based on the input of comments and reading of beginner js book
var rateOfPay, workHours, payCheck;
if ( !(rateOfPay > 0) ){
rateOfPay = prompt("ENTER YOUR HOURLY PAY", " ");
console.log(rateOfPay);
}
if ( !(workHours > 0) ){
workHours = prompt("ENTER HOW MANY HOURS YOU WORKED", " ");
console.log(rateOfPay);
}
Here's a quick and dirty way to handle this...
var rateOfPay, workHours;
while ( !(rateOfPay>0) ) {
rateOfPay = Number(prompt("Enter your hourly rate of pay", " "));
}
while ( !(workHours>0) ) {
workHours = Number(prompt("Enter hours worked", " "));
}
DEMO
Now, I didn't add a lot of error checking here, basically checking for a number over zero. Obviously, you can tweak as needed. What this code does is ask each question over and over until a valid response it entered.
do
{
// your code here...
// your else needs a break to exit do loop
else
{
//...
break;
}
}
while(true);
I took your code and edited some things,
when you said if rateOfPay is equal to " " or null, well it can't be because the var type is a number if theirs nothing in the prompt page then it will return 0, if their is text in it, it will return 0. So to fix this i just took out
if (rateOfPay === " " || rateOfPay === null);
and changed it to
if (rateOfPay === 0) {
I hope this fixes your problem!
heres the final:
var rateOfPay = Number(prompt("Enter your hourly rate of pay", ""));
var workHours = Number(prompt("Enter hours worked", ""));
if (rateOfPay === 0) {
alert("Please enter your Hourly rate in Dollars");
console.log(rateOfPay);
} else {
console.log(rateOfPay);
}
Try this, if you also want to clarify that the input was invalid:
var rateOfPay;
var workHours;
while (True) {
rateOfPay = Number(prompt("Enter your hourly rate of pay", " "));
if (rateOfPay == 0 || rateOfPay === null){
alert("Invalid rate of pay. Please enter a non-zero number");
} else {break;}
}
while (True) {
workHours = Number(prompt("Enter hours worked", " "));
if (workHours == 0 || workHours === null){
alert("Invalid work hours. Please enter a non-zero number");
} else {break;}
}
I don't know what your specific use case is, but you might want to use different comparisons, especially if you want to rule out negative or alphabetic inputs as well.

determining var type from prompt command and if else statement

I'm trying to write this exercise from a book:
Write a program to ask yourself, using prompt, what the value of 2 + 2
is. If the answer is "4", use alert to say something praising. If it
is "3" or "5", say "Almost!". In other cases, say something mean.
I made this attempt:
var input = "" || 'number'
prompt ("How many is 2+2 ?", input)
if (input = 4)
print ("Awesome !");
else if (input = 3 || input = 5)
print ("Close !");
else if (input = 'number'
print ("wrong number");
else if (input = 'random text')
print ("use numbers only!")
I know it is wrong. This is I intended to do:
I need to determine the type of var, not just the value. I need to make var either number or string (according to typeof). Why ? For prompt imput, because below else if condition, will be based on which type was inputted.
I know that exercise didn't asked it, but I want make it superior.
= is assignment. == is comparison.
To convert the string that prompt gives you to a number, use parseInt(input,10) - that said, JavaScript will typecast for you, so there's no real need here. You can even tell if the user entered something that isn't a number by testing isNaN(input) for your "use numbers only" result.
So something like this:
var input = parseInt(prompt("How much is 2 + 2?",""),10);
if( input == 4) alert("Awesome!");
else if( input == 3 || input == 5) alert("Almost!");
else if( input == 10) alert("No GLaDOS, we're working in Base 10 here.");
else if( input == 42) alert("That may be the answer to Life, the Universe and Everything, but it's still wrong.");
else if( isNaN(input)) alert("Use numbers only please!");
else alert("You are wrong!");
I'd personally suggest:
var guess = parseInt(prompt('What is 2 + 2?'), 10);
switch (guess) {
case 4:
console.log('Well done!');
break;
case 3:
case 5:
console.log('Almost!');
break;
default:
console.log('Seriously? No.');
break;
}
JS Fiddle demo.
Or, to be more functional about it:
function answerMath (sum) {
var actual = eval(sum),
guess = parseInt(prompt('What is ' + sum + '?'),10);
if (guess === actual) {
console.log('Well done!');
}
else if (guess + 1 === actual || guess - 1 === actual) {
console.log('Almost!');
}
else {
console.log('Seriously? No.');
}
}
answerMath ('2*3');
JS Fiddle demo.
Note that while eval() is the only means I could think of in this situation to evaluate the sum passed to the function as a string, I'm not entirely sure it's a good recommendation (albeit eval() has more bad press than it perhaps deserves, though it does present risks).
In most programming languages, = is assignment, and == tests for equality. So
a = 4 assigns the number 4 to the variable a. But a == 4 checks to see if a is equal to 4.
So for your code, you'd need:
var input = "" || 'number'
prompt ("How many is 2+2 ?", input)
if (input == 4)
print ("Awesome !");
else if (input == 3 || input == 5)
print ("Close !");
else if (input == 'number')
print ("wrong number");
else if (input == 'random text')
print ("use numbers only!")
I'm going to build on David Thomas's answer a little, because if you wanted to make it better, you could easily turn it into a little game.
var numa = Math.round(Math.random() * (100 - 1) + 1);
var numb = Math.round(Math.random() * (100 - 1) + 1);
var answer = numa + numb;
var guess = parseInt(prompt('What is ' + numa + ' + ' + numb + '?'), 10);
switch (guess) {
case answer:
alert('Well done!');
break;
case (answer - 1):
case (answer + 1):
alert('Almost!');
break;
default:
alert('Seriously? No.');
break;
}
Further things you could do would be to include a timer to see how long the user took to answer the question, and ask them if they way to play again when they get it right.
Here is a Fiddle: http://jsfiddle.net/6U6eN/

I cannot figure out how I can fix this if statement

var count=1;
var temp="";
var end= window.prompt('enter the length');
var b = parseInt(end);
while(true){
temp+="-";
count++;
if(count>b&&end!=null){
console.log("enter:" +end+ "= " + temp );
break;
}
}
I have this code which is suppose to give me the output of "-" for each number the user enters so if i the user enters 2 the output should be "--". But when the user enters a string or number zero the output should be just "-".
This is really just a simpler way of doing what you want, as comments say, isNaN is what you need to verify you actually get a number.
var length = parseInt(window.prompt('enter the length'), 10);
alert(new Array(isNaN(length) ? 2 : length + 1).join('-'));
var count = 1;
var temp = "";
var end = window.prompt('enter the length');
var b = parseInt(end);
while (true) {
temp += "-";
count++;
// if the user entered a valid integer that is not 0
if (!isNaN(b) && b !== 0) {
if (count > b && end != null) {
console.log("enter:" + end + "= " + temp);
break;
}
// else the user entered 0 or some other input that isn't an integer
} else {
console.log("enter:" + end + "= -");
break;
}
}​
FIDDLE
FIDDLE WITH ALERTS

Categories