skip to Main Content

I am making a javascript program in which the program asks the user whether they want to calculate distance, speed or time. The program works but I want to be able to make it where the user cannot enter a blank input as well as not allowing the program to continue if their input is not a number(where numbers are needed)

//This program asks the user to input whether they would like to calculate distance, time or speed.
//Depending their answer they get asked to input the values of the other two options
//The program then calculates either the speed, distance or time

function calculate(){
try{
    let question = prompt("Would you like to calculate Distance(km), Time(h) or Speed(kph)");
    let answer = question.toLowerCase();
        if(answer === "distance" && answer != ""){
            let time = Number(prompt("Please enter your time in hours:"));
            let speed = Number(prompt("Please enter your speed:"));
            let calculation = speed * time;
            console.log(`The Distance is: ${calculation} km`);
        }else if(answer === "time" && answer != ""){
            let distance = Number(prompt("Please enter your distance:"));
            speed = Number(prompt("Please enter your speed:"));
            let calculation2 = distance / speed;
            console.log(`Your Time is: ${calculation2} hours`);
        }else if(answer === "speed" && answer != ""){
            distance = Number(prompt("Please enter your distance:"));
            time = Number(prompt("Please enter your time in hours:"));
            calculation3 = distance / time;
            console.log(`Your speed is: ${calculation3} kph`)
        }else{
          calculate();
        }
}catch(e){
calculate();
}
}

let output = calculate();

3

Answers


  1. You can try to separate the functionality and write a generic function which recursively calls itself until a valid input is given.

    One of the possible implementation:

    function getTypePrompt() {
        const question = prompt("Would you like to calculate Distance(km), Time(h) or Speed(kph)");
        if ((question == null) || (question === "")) {
            return getTypePrompt();
        }
    
        switch (question) {
            case "distance":
            case "time":
            case "speed":
                return question;
        }
    
        return getTypePrompt();
    }
    
    function getNumberPrompt(message) {
        const response = prompt(message);
        if ((response == null) || (response === "")) {
            return getNumberPrompt(message);
        }
    
        const data = parseInt(response);
    
        if (!isNaN(data)) {
            return data;
        }
    
        return getNumberPrompt(message);
    }
    
    
    
    try {
        let question = getTypePrompt();
        let answer = question.toLowerCase();
        if (answer === "distance") {
            let time = getNumberPrompt("Please enter your time in hours:");
            let speed = getNumberPrompt("Please enter your speed:");
            let calculation = speed * time;
            document.write(`The Distance is: ${calculation} km`);
        } else if (answer === "time") {
            let distance = getNumberPrompt("Please enter your distance:");
            speed = getNumberPrompt("Please enter your speed:");
            let calculation2 = distance / speed;
            document.write(`Your Time is: ${calculation2} hours`);
        } else if (answer === "speed") {
            distance = getNumberPrompt("Please enter your distance:");
            time = getNumberPrompt("Please enter your time in hours:");
            calculation3 = distance / time;
            document.write(`Your speed is: ${calculation3} kph`)
        } else {
            calculate();
        }
    } catch (e) {
        document.write("Something went wrong!");
    }
    Login or Signup to reply.
  2. let 
      time,
      speed,
      calculation;
    
    time = Number(prompt("Please enter your time in hours:"));
    
    if(!time) {
      time = Number(prompt("Please enter your time in hours:"));
    }
    
    speed = Number(prompt("Please enter your speed:"));
    
    if(!speed) {
      speed = Number(prompt("Please enter your speed:"));
    }
    

    You can replace the Number by adding + just before prompting.
    time = +(prompt("Please enter your time in hours:"));

    If you want a faster, thought less clearer sometimes, you can use ternary operator

    which is basically like a short if-else

    time = !time ? +(prompt("Please enter your time in hours:")); : time;
    
    Login or Signup to reply.
  3. To prevent the user from entering a blank input, you can add a condition to check if the input is an empty string. To ensure that the user enters a number, you can use the isNaN() function to check if the input is not a number. Here’s an updated version of your code with these changes:

    function calculate() {
      let question = prompt("Would you like to calculate Distance(km), Time(h) or Speed(kph)");
      let answer = question.toLowerCase().trim();
    
      if (answer === "") {
        alert("Please enter a valid input.");
        calculate();
        return;
      }
    
      if (answer === "distance") {
        let time = Number(prompt("Please enter your time in hours:"));
        let speed = Number(prompt("Please enter your speed:"));
    
        if (isNaN(time) || isNaN(speed)) {
          alert("Please enter valid numbers.");
          calculate();
          return;
        }
    
        let calculation = speed * time;
        console.log(`The Distance is: ${calculation} km`);
      } else if (answer === "time") {
        let distance = Number(prompt("Please enter your distance:"));
        let speed = Number(prompt("Please enter your speed:"));
    
        if (isNaN(distance) || isNaN(speed)) {
          alert("Please enter valid numbers.");
          calculate();
          return;
        }
    
        let calculation2 = distance / speed;
        console.log(`Your Time is: ${calculation2} hours`);
      } else if (answer === "speed") {
        let distance = Number(prompt("Please enter your distance:"));
        let time = Number(prompt("Please enter your time in hours:"));
    
        if (isNaN(distance) || isNaN(time)) {
          alert("Please enter valid numbers.");
          calculate();
          return;
        }
    
        let calculation3 = distance / time;
        console.log(`Your speed is: ${calculation3} kph`);
      } else {
        alert("Please enter a valid input.");
        calculate();
        return;
      }
    }
    
    calculate();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search