You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript try-catch下重复用户输入及错误重试逻辑实现求助

解决方案

要实现输入错误时自动重试,核心是封装输入验证逻辑,并通过循环确保用户输入有效后再执行计算。以下是修改后的完整代码:

// 通用函数:获取有效的计算类型输入
function getValidCalculationType() {
  let type;
  while (true) {
    type = prompt("Would you like to calculate Distance(km), Time(h) or Speed(kph)");
    // 用户取消输入时退出
    if (type === null) {
      return null;
    }
    type = type.toLowerCase().trim();
    // 验证输入是否为预期类型
    if (["distance", "time", "speed"].includes(type)) {
      return type;
    }
    alert("Invalid input! Please enter Distance, Time or Speed.");
  }
}

// 通用函数:获取有效的数字输入(正数,避免计算错误)
function getValidNumberInput(promptText) {
  let num;
  while (true) {
    num = prompt(promptText);
    if (num === null) {
      return null;
    }
    num = Number(num.trim());
    // 验证是否为有效正数
    if (!isNaN(num) && num > 0) {
      return num;
    }
    alert("Invalid input! Please enter a positive number.");
  }
}

// 主计算逻辑,支持自动重试
function runCalculation() {
  try {
    const calculationType = getValidCalculationType();
    // 用户取消输入时终止
    if (calculationType === null) {
      console.log("Calculation cancelled.");
      return;
    }

    let result;
    switch (calculationType) {
      case "distance":
        const time = getValidNumberInput("Please enter your time in hours:");
        const speed = getValidNumberInput("Please enter your speed (kph):");
        if (time === null || speed === null) return;
        result = speed * time;
        console.log(`The Distance is: ${result.toFixed(2)} km`);
        break;
      case "time":
        const distance = getValidNumberInput("Please enter your distance (km):");
        const speedForTime = getValidNumberInput("Please enter your speed (kph):");
        if (distance === null || speedForTime === null) return;
        result = distance / speedForTime;
        console.log(`Your Time is: ${result.toFixed(2)} hours`);
        break;
      case "speed":
        const distanceForSpeed = getValidNumberInput("Please enter your distance (km):");
        const timeForSpeed = getValidNumberInput("Please enter your time in hours:");
        if (distanceForSpeed === null || timeForSpeed === null) return;
        result = distanceForSpeed / timeForSpeed;
        console.log(`Your Speed is: ${result.toFixed(2)} kph`);
        break;
    }
  } catch (error) {
    console.error("An error occurred:", error.message);
    // 出错后询问是否重试
    const retry = confirm("Something went wrong. Would you like to try again?");
    if (retry) {
      runCalculation();
    }
  }
}

// 启动程序
runCalculation();

关键改进点:

  • 封装输入验证函数:getValidCalculationType和getValidNumberInput通过循环持续请求输入,直到用户提供有效内容或取消输入,解决了重复输入的问题。
  • 严格输入校验:不仅验证是否为数字,还确保输入是正数,避免除以0或计算出无意义的负数结果。
  • 完整错误处理:try-catch捕获计算过程中的异常(比如意外的类型错误),并通过confirm询问用户是否重试。
  • 变量作用域优化:所有变量都在局部作用域声明,避免全局变量污染。
  • 用户友好提示:输入无效时弹出alert告知错误原因,用户取消输入时优雅终止程序。

内容的提问来源于stack exchange,提问作者JadenBotha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 18:17:43