0

I have to check (prompt window is obligatory) if a user entered a correct answer on these conditions:

  1. If a user entered a correct answer, alert 'you are correct'.
  2. If a user enters a wrong answer OR leaves it EMPTY, alert 'you are wrong' 3 If a user presses the cancel button nothing happens.
    var num1 = Math.floor(Math.random() * 9 + 1);
    var num2 = Math.floor(Math.random() * 9 + 1);
    var result = num1 * num2;
    var userInput = parseInt(prompt('What is ' + num1 + ' * ' + num2 + ' ?'));

    if (userInput === result){
        alert('You are correct!');
    } else if (userInput === '' || userInput !== result) {
        alert('You are wrong!');
    } else if (userInput === null) {
        alert('Cancelled!');
    }

What happens is that alert says 'you are wrong' even if I press cancel. I added cancelled alert just for an example. Any suggestions?

1
  • 2
    While prompt() does indeed return null when the user clicks Cancel, this information is lost when passed through parseInt(). You should check for the null response before attempting to parse the result. Commented Aug 15, 2019 at 21:59

3 Answers 3

1

You have two problems.

First, you are running the return value of prompt through parseInt before you test to see if it is an empty string or null.

Then you aren't distinguishing between null and "not the result".

  • Don't parseInt before you start your tests.
  • Test for null before you test for !== result.
  • Test for userInput === parseInt(result, 10) (always use a radix with parseInt)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! Also, how do I handle a situation where a user enters two or more numbers, the correct answer included, and it still says it's a wight answer?
0
if (userInput === result){
    alert('You are correct!');
} else if (isNaN(userInput)) {
    alert('Cancelled!');
} else if (userInput === '' || userInput !== result) {
    alert('You are wrong!');
}

Comments

0

The value returned from parseInt will never be strictly equal to null. Try testing the input before calling parseInt.

Here's one way that works:

const
  rand0To9 = () => Math.floor(Math.random() * 9 + 1),
  num1 = rand0To9(),
  num2 = rand0To9(),
  result = num1 * num2,
  input = prompt(`What is ${num1} * ${num2}?`);

if (input !== null){
  alert(`You are ${ parseInt(input, 10) == result ? "correct" : "wrong" }!`);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.