Java单位转换程序异常处理:如何避免输入格式错误崩溃?
问题解决:单位转换程序异常处理与书籍推荐
一、修复输入格式错误导致的崩溃问题
问题根源
原代码直接调用stdio.nextDouble()读取数值,当输入不是合法数字(比如只输入"inches")时,会触发InputMismatchException,且无异常捕获机制,导致程序直接崩溃。另外每次循环新建Scanner对象属于冗余操作。
修复方案
- 将
Scanner实例移到循环外部,复用同一个实例 - 使用
hasNextDouble()先校验输入是否为合法数字,若不合法则输出提示并清空输入缓冲区,回到输入步骤 - 保留原有单位校验逻辑,确保格式错误和单位错误都能给出友好提示
修改后的完整代码
import java.util.Scanner; public class UnitConversionTextBook { public static void main(String[] args) { String units; double measurement; double inches, feet, yards, miles; System.out.println(""" Enter measurements in inches, feet, yards, or miles. Some examples: 1 inch or 17 feet or 2.73 miles You can use the abbreviations: in ft yd mi Please press enter after typing your measurement. I will also convert your input into the other units of measurements. """); // 复用Scanner实例,避免重复创建 Scanner stdio = new Scanner(System.in); while (true) { System.out.print("Enter your measurement, or 0 to end: "); // 先判断输入是否为合法数字 if (!stdio.hasNextDouble()) { // 读取并丢弃无效输入,防止死循环 String invalidInput = stdio.nextLine(); System.out.printf("错误:输入格式不正确,请遵循「数值+单位」格式,例如\"56 inches\"。你输入的内容是:%s%n", invalidInput); continue; } measurement = stdio.nextDouble(); units = stdio.next().toLowerCase(); if (measurement == 0) { break; } if (units.equals("inch") || units.equals("inches")|| units.equals("in")) { inches = measurement; } else if (units.equals("foot") || units.equals("feet")|| units.equals("ft")) { inches = measurement * 12; } else if (units.equals("yard") || units.equals("yards")|| units.equals("yd")) { inches = measurement * 36; } else if (units.equals("mile") || units.equals("miles")|| units.equals("mi")) { inches = measurement * 12 * 5280; } else { System.out.println("Sorry, but I don’t understand \"" + units + "\"."); continue; } feet = inches / 12; yards = inches / 36; miles = inches / (12*5280); System.out.println(); System.out.printf(""" That’s equivalent to: %14.5g inches %14.5g feet %14.5g yards %14.5g miles """, inches, feet, yards, miles); System.out.println(); } // 关闭Scanner资源 stdio.close(); } }
二、《Intro to Programming using Java》是否适合Java学习
这本书非常适合Java入门学习者:
- 内容循序渐进,从基础编程概念(变量、循环、分支)到Java面向对象特性都有清晰讲解,贴合新手学习路径
- 配套示例程序(比如这个单位转换程序)贴近实际应用,能帮助学习者快速理解知识点并动手实践
- 讲解风格通俗易懂,没有过多晦涩术语,适合刚接触编程或Java语言的人打基础
如果是已有编程基础、想要深入Java高级特性(如并发、JVM原理)的学习者,这本书的深度可能不够,但作为入门阶段的学习资料完全够用。
内容的提问来源于stack exchange,提问作者whiteTreaty
相关产品推荐
相关产品推荐

