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
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:
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
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: