Home > Mobile >  adding two numbers in prompt, verify both inputs are numbers, alert if wrong format
adding two numbers in prompt, verify both inputs are numbers, alert if wrong format

Time:09-06

I need to ask the user in a prompt for two numbers, add them together then give an answer, it should also verify both inputs are number and if not prompt them with wrong data. help?

function addTwoNumbers() {
    let num1 = parseInt(prompt("Provide the first number:"));   
    let num2 = parseint(prompt("Provide the second number:"));    
    if(isNaN(num1) || isNaN(num2)) {        
        alert("The final score is: ", (num1 num2));   
    }
    else {
        alert("Wrong data");
    }
}

CodePudding user response:

Your if clause is wrong. If we look at it:

if(isNaN(num1) || isNaN(num2))...

What you are doing here is checking if num1 OR num2 are not a number then it should add it. What you really want to do here is check if BOTH are numbers. So you have two possibilities here:

if(isNaN(num1) || isNaN(num2)) {
   alert("Wrong data");
}
else {
  alert("The final score is: ", (num1 num2)); 
}

This checks is either of the num variables are not a number. If one or the other is not a number, then an error should be shown.

if(!isNaN(num1) && !isNaN(num2)) {
   alert("The final score is: ", (num1 num2)); 
}
else {
  alert("Wrong data");
}

In this one, we are checking if, for both numbers, isNaN returns false, meaning that they are both a number.

CodePudding user response:

In your second statement:

let num2 = parseInt(prompt("Provide the second number:")); 

parseintparseInt

Also, keep in mind that you are currently showing the user the final score if one of both number is NOT a number.

if(!isNaN(num1) && !isNaN(num2)) {   
       alert("The final score is: ", (num1 num2));   
}

This should do the job.

  • Related