我正在做一个javascript程序,程序会问用户是想计算距离、速度还是时间。该计划的工作,但我希望能够使它的地方,用户不能输入一个空白的输入,以及不允许程序继续,如果他们的输入不是一个数字(在数字是必要的)
//这个程序要求用户输入他们是否想计算距离、时间或速度。//根据他们的答案,他们被要求输入其他两个选项的值//然后程序计算速度,距离或时间
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();
2条答案
按热度按时间643ylb081#
您可以在提示前加上+来替换数字。
time = +(prompt("Please enter your time in hours:"));
如果你想要一个更快,更清晰的想法,你可以使用ternary operator
基本上就是一个简短的if-else
ki1q1bka2#
您可以尝试分离功能并编写一个泛型函数,该函数递归地调用自身,直到给出有效的输入。
可能的实现之一: