what's wrong with my code here - javascript

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.

Related

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))

Taking two mathrandom values and adding them on loop

I have to make a game of dice where I add the values of both the dice and give the sum. You get another turn if both the dice end up on the same number (such as 2 and 2 which is 4) then you roll the dice again and the 2 new numbers get added to the previous sum (like 4 mentioned earlier).
For example -
1st try 3 and 3, sum is 6.
2nd try 4 and 5, sum is 6 + 4 + 5 = 15
I'm able to get the first sum right, but the subsequent numbers are getting messed up sometimes even giving twice as much.
function oneRandom(){
var my1 = Math.floor(Math.random() * 6 ) +1 ;
var my2 = Math.floor(Math.random() * 6 ) +1 ;
var num1 = Number(my1);
var num2 = Number(my2);
var sum = num1 + num2;
console.log(sum);
var resultfield = document.getElementById("total").innerHTML = "<h1>"+sum+"</h1>";
document.getElementById("cilc").style.display = "none";
if (getImage.src == get2.src){
document.getElementById("cilc").style.display = "block";
var sum2 = num1 + num2;
var total = sum2 + sum;
var resultfield = document.getElementById("total").innerHTML = "<h1>"+total+"</h1>";
}
}
The getImage and get2 are arrays to match dice images to give another turn in case of same numbers loading.
You can try this,
function rollDice (times) {
var num1 = Math.floor(Math.random() * Math.floor(6));
var num2 = Math.floor(Math.random() * Math.floor(6));
console.log(times, num1, num2);
var total = num1 + num2;
return num1 === num2 ? total + rollDice(times + 1) : total;
}
console.log(`result is ${rollDice(0)}`);

adding numbers in positive and negative numbers in a javascript prompt

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.

JS sum of 2 numbers return a bad result

I calculate a lot of number with javascript. In some calculation i have a bad result.
Exemple: http://jsfiddle.net/6et8d10c/
var num1 = 2.01;
var num2 = 22.29;
var result = num1 + num2; //24.29 (should be 24.30)
For now I fix with:
(2.01*100 + 22.29*100) / 100 = 24.30
That's not perfect. Why can't i calculate 2.01 + 22.29 ?

Trying to get my JavaScript to work out the 2 numbers entered to get calculated by pc.

Just wondering if anyone can work out why I keep getting for eg. 3+3=33 and not 6.
The rest of the coding works fine for the divide and times its the addition that keeps stuffing up and wont come up with the correct answer.. please help if you can.
here is my code:
<html>
<head>
<title>Practical Task 8 </title>
</head>
<body>
<button onclick="myFunction()">Press & Enter First Digit & Second Digit</button>
<script type="TEXT/JavaScript">
function myFunction()
{
var x=prompt("Please enter first number","0");
var y=prompt("Please enter second number","0");
var sum = x;
var sum2 = y;
var n = (x * y);
var n2 = (x / y);
var n3 = (x + y);
document.write(sum + " + " + sum2 + " = " + n3);
document.write("<BR>" + sum + " * " + sum2 + " = " + n);
document.write("<BR>" + sum + " / " + sum2 + " = " + n2);
}
</script>
</body>
</html>
You're performing string concatenation, not integer addition.
Use parseInt first:
x = parseInt( x, 10 );
y = parseInt( y, 10 );
MDN recommends always specifying the radix (the 10 part) to avoid problems, such as if a user prepends a number with 0 (where it'll be parsed as octal), or if different browsers have a different default radix (wtf, I know!).
You have to do this because the output of prompt is always a string, even if it's a number (e.g. "10" or "0123"), you need to tell JavaScript to interpret the data as a number (use parseInt if it's an integer (a whole number), or use parseFloat if you'll accept numbers with decimal places). Confusingly the + operator works for both string and number types, where it performs either concatenation (i.e. joining strings together like glue) or addition depending on the type of its operands.
Because your code is adding strings.
User input is always string.
You need to parseInt(x, 10) and parseInt(y, 10) to parse the string value into int base 10.

Categories