adding numbers in positive and negative numbers in a javascript prompt - javascript

I'm trying to write a script on a webpage that presents the user with an arithmetic problem (EG what is 2 + -4) and asks for the answer using a prompt. then give them the feedback using an alert box. the integers have to be between -10 and 10 so far I've tried this and no luck:
var num = Math.Floor((Math.random() * -10) + 10);
var numPrompt = prompt("what is " + (num + num));
alert(numPrompt);
then I tried:
var num = Math.Floor((Math.random() * -10) + 10);
var numPrompt = prompt( "what is " + (parseInt(num) + parseInt(num)) );
alert(numPrompt);
both failed, but why?

Here's something similar to what you want:
var num1 = Math.floor((Math.random() * -21) + 11);
var num2 = Math.floor((Math.random() * -21) + 11);
var userAnswer = prompt('What is ' + num1 + ' + ' + num2 + '?');
if (userAnswer.trim() !== '' && +userAnswer === num1 + num2) {
alert('Correct');
} else {
alert('Wrong');
}
Since num1 and num2 are numbers being generated by the Javascript, we can simply compare the number +userAnswer to num1 + num2.
The reason for doing +userAnswer is the userAnswer variable contains the answer returned by the prompt function, which is a string, so putting a + sign infront of it converts it to a number.
I like +userAnswer more than parseInt because parseInt('5a') returns 5 where as +'5a' returns 0.
The only we have to watchout for is +'' or +' ' returns 0 so we have to do an additional check to make sure the user didn't just press enter without typing a number.

Related

Uncaught SyntaxError: unexpected token: string literal in javascript. I can't figure out what's wrong [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
This is my code, a simple sequel of function were I generate two number, one for the user, one for the PC and who scores the highest number win the game.
Firefox has come out with Uncaught SyntaxError: unexpected token: string literal error, I checked my code and everything seems ok to me, I can't figure out what's wrong and generates that error
// Generate a random number between 1 and 6 both for user and PC.
// Who does the highest score win.
//I create the random number for user and PC
var userNumber = getRandomNumber(1, 6);
var pcNumber = getRandomNumber(1, 6);
console.log(userNumber);
console.log(pcNumber);
//With highestScore function the winner comes out
var whoWon = highestScore(userNumber, pcNumber);
console.log(whoWon);
//I use this function to obtain the random number
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1) ) + min;
}
//Function highestScore tell who's won the game
//matchMessage tells how the winner or the eventual tie has come
//The return is obviously matchMessage
function highestScore (num1, num2) {
var matchMessage = 'Your number is ' + num1 ', PC number is ' + num2 ', tie!!';
if (num1 > num2) {
matchMessage = 'Your number is ' + num1 ', PC number is ' + num2 ', congrats you've won';
} else if (num1 < num2) {
matchMessage = 'Your number is ' + num1 ', PC number is ' + num2 ', you lost...';
}
return matchMessage;
}
You are missing a plus + sign while adding the strings with variables.
What you are doing:
'Your number is ' + num1 ', PC number is '
What it should be:
'Your number is ' + num1 + ', PC number is '
When you are using the same type of quote in a string then you have two ways to correct it:
Use different strings, like:
", congrats you've won"
Or you can escape that string using \, Like
', congrats you\'ve won'
Try this:
// Generate a random number between 1 and 6 both for user and PC.
// Who does the highest score win.
//I create the random number for user and PC
var userNumber = getRandomNumber(1, 6);
var pcNumber = getRandomNumber(1, 6);
console.log(userNumber);
console.log(pcNumber);
//With highestScore function the winner comes out
var whoWon = highestScore(userNumber, pcNumber);
console.log(whoWon);
//I use this function to obtain the random number
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
//Function highestScore tell who's won the game
//matchMessage tells how the winner or the eventual tie has come
//The return is obviously matchMessage
function highestScore(num1, num2) {
var matchMessage = 'Your number is ' + num1 + ', PC number is ' + num2 + ', tie!!';
if (num1 > num2) {
matchMessage = 'Your number is ' + num1 + ', PC number is ' + num2 + ', congrats you\'ve won';
} else if (num1 < num2) {
matchMessage = 'Your number is ' + num1 + ', PC number is ' + num2 + ', you lost...';
}
return matchMessage;
}

Adding two Var numbers together?

I assigned three cells of numbers and then I wanted to sum them together,
var num1, num2, num3: number;
num1 = prompt("Enter num1:");
num2 = prompt("Enter num2:");
num3 = prompt("Enter num3:");
document.write((num1 + num2 + num3));
alert((num1 + num2 + num3));
and if i enter 10 , 20 , 30 the out put is : 102030 ,
and its need to be 60...
Thanks for the helpers.
The prompt() function gives you a string so you have to convert it a number.
You can do what you want this way:
var num1, num2, num3;
num1 = parseInt(prompt("Enter num1:"));
num2 = parseInt(prompt("Enter num2:"));
num3 = parseInt(prompt("Enter num3:"));
document.write((num1 + num2 + num3));
alert((num1 + num2 + num3));
If you wish to use floats instead, simply replace parseInt with parseFloat.
The prompt() function work with string Values,
If you want to return type number add a (+) after the (=),
Take a look at this code and understand better what I meant :
let testPrompt1;
let testPrompt2;
testPrompt1 = prompt("Enter test 1:"); // Enter number
testPrompt2 = + prompt("Enter test 2:"); // Enter number
document.write("Type of test 1" + typeof testPrompt1 ); // String !!
document.write("Type of test 2" + typeof testPrompt2 ); // Number !!
// Add (+) before the (=) !!!!
let num1, num2, num3;
num1 =+ prompt("Enter num1:"); // 10
num2 = + prompt("Enter num2:");// 20
num3 = + prompt("Enter num3:");// 30
document.write((num1 + num2 + num3)); // Output 60
alert((num1 + num2 + num3)); // Output 60
I also suggest adding a variable of the result and not printing everything in one line for a better understanding of the code.
let num1, num2, num3, res;
num1 = + prompt("Enter num1:");
num2 = + prompt("Enter num2:");
num3 = + prompt("Enter num3:");
res = num1 + num2 + num3;
document.write("Result : " + res); // Output 60
alert("Result : " + res); // Output 60
Make sure you convert them from string to number:
alert((Number(num1 ) + Number(num2) + Number(num3));
JS is treating numbers like strings now, so it concatinates them. Try cast them to int(integers) so they can be added.Write smth like:
document.write(Number(num1) + Number(num2) + Number(num3)))
alert(Number(num1)+Number(num2)+Number(num3))

what's wrong with my code here

Can somebody help me with this. Here I have a set of 3 different numbers as strings that I get from a user and I also have another 3 randomly generated numbers that I want to compare with the set of numbers that I get from a users but since I'm not gonna do any calculations with the number I didn't see any reason to convert them so I'm trying to compare them as strings
function radGenerator(userno1,userno2,userno3,wnum1, wnum2, wnum3,dvresult) {
$(wnum1).text("" + Math.floor((Math.random() * 10) + 1));
$(wnum2).text("" + Math.floor((Math.random() * 10) + 1));
$(wnum3).text("" + Math.floor((Math.random() * 10) + 1));
var num1 = num2 = num3 = "";
if($(userno1).text()== $(wnum1).text()||
$(userno1).text()== $(wnum2).text()||
$(userno1).text()== $(wnum3).text()){
num1 = $(userno1).text();
}
if($(userno2).text()== $(wnum1).text()||
$(userno2).text()== $(wnum2).text()||
$(userno2).text()== $(wnum3).text()){
num2 = $(userno2).text();
}
if($(userno3).text()== $(wnum1).text()||
$(userno3).text()== $(wnum2).text()||
$(userno3).text()== $(wnum3).text()){
num3 = $(userno3).text();
}
$(dvresult).text("Winning Numbers: " + num1 +" "+ " "+ num2 + " "+ num3);
}
radGenerator("#uans1","#uans2","#uans3","#wno1", "#wno2", "#wno3","#divresult");
In order to compare strings in JavaScript, you should the localeCompare() function. "string".localeCompare("otherString"); will return 1 because "string" comes after "otherString". The function would return 0 if they are equal and -1 if the first string comes before the string you are comparing it to.

JavaScript stops execution half way and evaluates wrong answer?, Console.log is correct

I didn't think this was possible until console.log(); shown me that whats happening is impossible.
I can't understand how this is possible it's like those variables are being modified before code execution finishes.
I got this JavaScript code with debugging in it.
It's wrapped in this.
$('#buyAmountInput').keyup(function () {
var buyAmount = parseFloat($(this).val());
var totalPrice = 0;
var max = $(this).attr("max");
var min = $(this).attr("min");
if (buyAmount != $(this).val()) {
if (isNaN(buyAmount)) {
buyAmount = 1;
$(this).val('');
} else {
$(this).val(buyAmount);
}
} else {
if (buyAmount > max) {
buyAmount = max;
$(this).val(buyAmount);
} else if (buyAmount < min) {
buyAmount = min;
//$(this).val(buyAmount);
}
}
totalPrice = buyAmount * unitPrice;
//lots of code trimmed off here.
largessAmount = Math.round(buyAmount * largessRule.rebate) / 100;
////
console.log("Buy amount " + buyAmount + " LargessRebate " + largessRule.rebate);
console.log("Total Price " + totalPrice);
console.log("Largess Amount " + largessAmount);
console.log("New rate " + Number(totalPrice / (buyAmount + largessAmount)).moneyFormat());
console.log("No .moneyFormat() New rate " + Number(totalPrice / (buyAmount + largessAmount)));
console.log("( " + totalPrice + " / ( " + buyAmount + " + " + largessAmount + " ))");
////
$('#unitPrice').html(Number(totalPrice / (buyAmount + largessAmount)).moneyFormat());
});
Debug looks like this
Buy amount 5000 LargessRebate 20
Total Price 4250
Largess Amount 1000
New rate 0.71
No .moneyFormat() New rate 0.7083333333333334
( 4250 / (5000 + 1000))
function fastKeyListener content_script.js:208
Buy amount 5000 LargessRebate 20
Total Price 4250
Largess Amount 1000
New rate 0.00 //<- What happened here
No .moneyFormat() New rate 0.00008499830003399932 //<- What happened here
( 4250 / (5000 + 1000)) //<- Third line executed this will give good rate..
Even if the variables are global and this code is in a keypress up jQuery callback function.
The variables are printed before they are executed by console.log() and they are correct but the answer is dead wrong.
Here is the moneyFormat() which I don't think could be the problem could it?
var effective_bit = -2;
Number.prototype.moneyFormat = function () {
var num = this;
sign = (num == (num = Math.abs(num)));
num = Math.floor(num * Math.pow(10, -effective_bit) + 0.50000000001);
cents = num % Math.pow(10, -effective_bit);
num = Math.floor(num / Math.pow(10, -effective_bit)).toString();
for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
num = num.substring(0, num.length - (4 * i + 3)) + ', ' + num.substring(num.length - (4 * i + 3));
if (effective_bit < 0) {
if (cents < 10 && effective_bit == '-2') cents = "0" + cents;
money = (((sign) ? '' : '-') + num + '.' + cents);
} else {
money = (((sign) ? '' : '-') + num);
}
return money;
};
I didn't post the whole code as it's very large, but you can see it live here
Just put into the Unit to buy of 4999, then scroll to 5000 it's all good.. try putting like 5001 or 50000 it will reset it to 5000 and give wrong answer in the process.
EDIT:
could of simplified the question to why does the console.log() functions evaluate incorrect answer if the same equation generated with the same variables just 1 line after in execution after gives correct answer, even on calculator.
Like some quantum going on here, bear with me there is nothing I could have done from 1 line to another line during that code-execution no breakpoints were set nothing plus those callbacks are functions generated in their own sandbox I believe so they are like ajax threads all working to complete sooner or later they all work separately from each other, so nothing working together here to mess it up. What you think could possibly happen here? some temporarily corruption or something?
This occurs sometimes when doing claulations using string variables.
Try converting the buyAmount and any variable that came from HTML to number before any calculation.
You can use the Number() function or parseFloat().
http://jsfiddle.net/rcdmk/63qas2kw/1/

unable to get a message to display [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have to create a code which asks the user to input two numbers. The program needs to multiply the two numbers and then display the answer in a displayed message. ie: 5 x 7 is 35! (assuming the numbers the user inputed were 5 and 7.)
Here is the code I have now.
<title></title>
<script type="text/javascript">
var num1 = 0;
var num2 = 0;
var calculatedNum = 0;
function calculation() {
//create a integer variable called num2
//Purpose: second variable
var num2 = 0; // integer second variable
//create a integer variable called calculatedNum
//Purpose: num1 x num2
var calculatedNum = 0; // integer num1 x num2
//ask user '"Please type the first number"'
//and put the answer in num1
num1 = prompt("Please type the first number");
//ask user '"Please type the second number."'
//and put the answer in num2
num2 = prompt("Please type the second number.");
//Tell user: num1 + "x" + num2 + "=" + calculatedNum
alert (num1 + "x" + num2 + "=" + calculatedNum);
} // end calculation function
}end program
</script>
Try it
var num1 = 0;
var num2 = 0;
var calculatedNum = 0;
function calculation() {
num1 = prompt("Please type the first number");
num2 = prompt("Please type the second number.");
calculatedNum = (num1*num2);
alert(num1 + "x" + num2 + "=" + calculatedNum);
}
use calculation(); to call :)
You've overcomplicated things for yourself. Just do this:
<script>
var num1 = prompt('Please type the first number'),
num2 = prompt('Please type the second number');
alert(num1 + "x" + num2 + "=" + num1 * num2);
</script>
Demo 1
Or, if you want to wrap this in a function so you can call it from somewhere else:
<script>
function calculation() {
var num1 = prompt('Please type the first number'),
num2 = prompt('Please type the second number');
alert(num1 + "x" + num2 + "=" + num1 * num2);
};
calculation();
</script>
Demo 2
<title></title>
<script type="text/javascript">
var num1 = 0;
var num2 = 0;
var calculatedNum = 0;
function calculation() {
//create a integer variable called num2
//Purpose: second variable
var num2 = 0; // integer second variable
//create a integer variable called calculatedNum
//Purpose: num1 x num2
var calculatedNum = 0; // integer num1 x num2
//ask user '"Please type the first number"'
//and put the answer in num1
num1 = prompt("Please type the first number");
//ask user '"Please type the second number."'
//and put the answer in num2
num2 = prompt("Please type the second number.");
calculatedNum = num1*num2;
//Tell user: num1 + "x" + num2 + "=" + calculatedNum
alert (num1 + "x" + num2 + "=" + calculatedNum);
} // end calculation function
calculation();
</script>
This works as intended.
you were having an extra "}end program" at the end.

Categories