Skywhisky
Skywhisky

Reputation: 45

How to use a Math.random function in association with an IF statement

I am trying to output different messages based upon the output of a function that uses the math.random function to generate a number between 1 and 4.

function roll()
{
return Math.floor(Math.random()*4+1)  
}

When a button is pressed the function is called and a global variable 'a' is assigned to the result of the roll function.

var a;
function buttonPressed() {
roll() 
a = roll() 
answertq = (x*y);

The following code essentially means that if the answer the user provides in the answer box is correct then depending upon the result of the roll function output a different message as below.

if (parseInt(document.getElementById("inputVal").value) == answertq) 
{
    if (a=1) 
    {
        window.alert("Very good!");
    }
    else if (a=2)
    {
        window.alert("Excellent!");
    }
    else if (a=3)
    {
        window.alert("Correct, Nice work");
    }
    else if (a=4)
    {
        window.alert("Correct - Keep up the good work");
    }

}

Except that when I do this I always get the first response ("Very good!") every time the question is correct. Meaning that there is something wrong with the roll function in that it keeps assigning 1 to the global variable 'a' or something else I have not spotted. Any help would be much appreciated. I have provided two screenshots of the problem below.

[1] https://i.sstatic.net/28YcV.jpg "Example One" [2] https://i.sstatic.net/ANG2t.jpg "Example Two"

Upvotes: 1

Views: 5759

Answers (4)

Tim Vermaelen
Tim Vermaelen

Reputation: 7059

Why don't you use an array for your messages? That way you can use the random number as an index for the array.

var msg = [
    "Very good!",
    "Excellent!",
    "Correct, Nice work",
    "Correct - Keep up the good work"
];

function randomMsg (){
    var random = Math.floor(Math.random() * 4);
    alert(msg[random]);
}

edit: arrays are zero based so no "+1"

Upvotes: 1

dane
dane

Reputation: 631

All of your if statements are using the assignment operator "=" not the comparison operator "==":

if (parseInt(document.getElementById("inputVal").value) == answertq) {
    if (a==1) {
        window.alert("Very good!");
    }

etc...

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172448

Except that when I do this I always get the first response ("Very good!") every time the question is correct.

The reason is because you are not comparing the values you are assigning. == is for comparison and = is for assignment.

Try this:

if (a==1) 
    {
        window.alert("Very good!");
    }
    else if (a==2)
    {
        window.alert("Excellent!");
    }
    else if (a==3)
    {
        window.alert("Correct, Nice work");
    }
    else if (a==4)
    {
        window.alert("Correct - Keep up the good work");
    }

Upvotes: 2

DhruvPathak
DhruvPathak

Reputation: 43245

You need to compare a==1 not assign a=1

Upvotes: 1

Related Questions