3

You'll have to forgive me, I'm new to JavaScript...like a few weeks new. Anyway, I created a code using JavaScript to generate two random numbers, ask to add them, and give a "That is correct/that is incorrect" answer based on the users response. I wanted to add the other signs (-,*,/) to the equation and decided to try my hand at arrays to do so. Here is what I have so far:

<head>
    <meta charset="utf-8" />
    <title>Math Games</title>
</head>

<body>
    <script>
        var Answer;
        var numbers=new Array();
        var signs=new Array();
        var Signs2=new Array();
        var SignNoQuote=new Array();
        numbers[0]=(Math.floor(Math.random() * 10 + 1));
        numbers[1]=(Math.floor(Math.random() * 10 + 1));
        signs[0]="+";
        signs[1]="-";
        signs[2]="*";
        signs[3]="/";
        SignNoQuote[0]="+";
        SignNoQuote[1]="-";
        SignNoQuote[2]="*";
        SignNoQuote[3]="/";
        Signs2[0]=(Math.floor(Math.random() * 4));          
        Answer=window.prompt("What is " + numbers[0] + signs[Signs2[0]] + numbers[1] + "?");
        if(Answer==numbers[0] + SignNoQuote[Signs2[0]] + numbers[1])
        {
            window.alert("That's Correct!");
        }
        else
        {
            window.alert("That is Incorrect");
        }
    </script>

    <a href="file:///E:/ECS/Legitimate%20Work/mathtest.html">Refresh</a>

</body>

It asks the question correctly, but when the right answer is given, it says that it is incorrect. I tried removing the quotation marks from the values of the "SignNoQuote" array hoping it would work, but when it is run that way, none of the script will run and the debugger claims it to be a syntax error? What am I doing wrong and how can I fix it?

quickshiftin
  • 66,362
  • 10
  • 68
  • 89
  • 2
    All your values are strings. `numbers[0] + SignNoQuote[Signs2[0]] + numbers[1]` won't perform a mathematical computation, it will simply concatenate the three strings. You cannot "store" an operator in a variable. – Felix Kling Mar 05 '14 at 17:48
  • you could try to achieve something with `eval()`. EDIT: actually you can solve your problem with `eval()`. – andy Mar 05 '14 at 17:49
  • FWIW, you don't have to use an array for everything. `Signs2` doesn't seem like it has to be an array. You should also use more meaningful variable names. – Felix Kling Mar 05 '14 at 17:54

3 Answers3

5

If you want something specific to the use case you have, this will work nicely:

//A mapping from the symbol for an operation to
//the function that executes it.
var opFunction = {
    "+": function (x, y) { return x + y; },
    "-": function (x, y) { return x - y; },
    "*": function (x, y) { return x * y; },
    "/": function (x, y) { return x / y; }
};

//Gets the operation symbol.
var op = SignNoQuote[Signs2[0]];

//Looks up the function for the operation,
//then calls it with your numbers as operands.
var result = opFunction[op](numbers[0], numbers[1]);

However, if you need something general purpose for evaluating mathematical expressions, Brad's answer provides what you need.

Timothy Shields
  • 75,459
  • 18
  • 120
  • 173
3

If I'm understanding the problem, you are trying to use a string of a symbol to do math.

numbers[0] + SignNoQuote[Signs2[0]] + numbers[1]

The trouble with this is that + means concatenation when used in the context of strings. You don't have a + operator in code, you have the string of text with one character, +. These are fundamentally different. It's no different than this:

numbers[0] + '+' + numbers[1]

.... which results in something like this:

"1+2"

What you need to do is actually execute that input somehow, such as with eval(). Unfortunately, this is where you run into some scary security issues, allowing users to execute whatever they want. In some contexts this can be safe, but usually it isn't.

There are options for you to run this equation. See this question for details: Evaluating a string as a mathematical expression in JavaScript

Community
  • 1
  • 1
Brad
  • 159,648
  • 54
  • 349
  • 530
  • Technically, they wouldn't be `eval`ing anything that came from the user, their operators and operands are all generated in the code. Not that it's a good idea anyway... – Matt Burland Mar 05 '14 at 17:52
  • @MattBurland Fair enough. Timothy suggested a valid solution in those cases. But, I figured I would explain the string problem I think the question is about. – Brad Mar 05 '14 at 18:03
0

When you're checking you're answer, you use a comparison to:

numbers[0] + SignNoQuote[Signs2[0]] + numbers[1]

But assuming you want it to multiply, what that actually is, is something like:

2 + "*" + 1

Which is not the same as:

2 * 1

The easiest way to do this would probably be with a if ... else if ... else if ... statement. Something like:

var answerCorrect = false;
if (SignNoQuote[Signs2[0]] == "+") {
    answerCorrect = (Answer == numbers[0] + numbers[1]);
} else if (SignNoQuote[Signs2[0]] == "*") {
    answerCorrect = (Answer == numbers[0] * numbers[1]);
} else if (etc ...

then:

if(answerCorrect) {
    window.alert("That's Correct!");
} else {
    window.alert("That is Incorrect");
}
David Downes
  • 1,145
  • 10
  • 24