Home > database >  Checking an integer's value
Checking an integer's value

Time:04-08

I got this javascript exercise from my school. and I got this error. I don't understand what this error means.

Incorrect output: your program printed "20Invalid", but should have printed "20The"

The webpage is asking for the user's age. The input value has already been fetched, but you have to fill in the missing code. When the page calls the function checkAge(), first print in the console "The input age: [age]", followed by one of the following, depending on the value:

18 years or more: "The user is an adult."

Under 18 years, but over 0 years: "The user is not yet an adult."

Otherwise: "Invalid input!"


function checkAge() {
    var age = document.getElementById("age").value;
console.log("Input age: "   age);
        if (age <= 18 ){
            console.log("The user is an adult.");
        }
        else if (0 <= age && age < 18){
            console.log("The user is not yet an adult.");
        }
        else {
            console.log("Invalid input!");
        }
}

CodePudding user response:

This line:

   if (age <= 18 ){
       console.log("The user is an adult.");
   }

should be changed to:

        if (age >= 18 ){
            console.log("The user is an adult.");
        }

You want to check if user is greater that 18 for adult, not <= 18

CodePudding user response:

I would change it to this.

function checkAge() {
  var age = document.getElementById("age").value

  console.log("Input age: "   age);

  if (age >= 18 ){
      console.log("The user is an adult.");
  }
  else if ( age < 18){
      console.log("The user is not yet an adult.");
  }
  else {
      console.log("Invalid input!");
  }
}

The things I have changed are:

if (age <= 18 ) - I have changed it to >= because this checks if age is GREATER or EQUAL too 18 instead of LESS THAN or EQUAL too.

else if ( age < 18) - I have removed 0 <= age && as this checks if age is LESS THAN or EQAUL to 0 AND age is LESS THAN 18. Where as you only need to check if age is less than 18

CodePudding user response:

age = document.getElementById("age").value; will return a string.

You first need to convert it into an integer. You can do this using parseInt(age)

var age = parseInt( document.getElementById("age").value; )

now, This function will convert it into integer value and you can compare it easily.

  • Related