Java中显示boolean类型值时触发InputMismatchException异常如何解决
错误排查结果
- 核心错误原因:
input.nextBoolean()方法仅支持输入字面量true/false(大小写不敏感)才能正确解析为布尔值,你输入的national属于字符串类型,和预期的布尔输入不匹配,因此触发InputMismatchException异常。 - 隐藏问题:调用
input.nextDouble()读取价格后,输入缓冲区会残留未被读取的换行符,若后续调用nextLine()方法会直接读取到空字符串,需要提前处理。
修复后的主类代码
import java.util.Scanner; public class CarApp { public static void main(String[] args) { //declaration Scanner input = new Scanner(System.in); String model, brand, typeInput; double price; boolean type; Car c = new Car(); System.out.println("Enter a car Model : ");//X70/Starex model = input.nextLine(); c.SetCar_Model(model); System.out.println("\nEnter a car Brand : ");//Proton/Hyundai brand = input.nextLine(); c.SetCar_Brand(brand); System.out.println("\nEnter the car price : RM");//95000.00/170000.00 price = input.nextDouble(); c.SetCar_Price(price); // 吃掉nextDouble残留的换行符 input.nextLine(); System.out.println("\nEnter the car brand [national/imported] : ");//national/imported car typeInput = input.nextLine(); // 自行将输入的字符串转换为布尔值:national对应true(国产车),imported对应false(进口车) type = typeInput.equalsIgnoreCase("national"); c.SetCar_Type(type); //output System.out.println(c.toString()); // 输出中文车辆类型 System.out.println("车辆类型:" + (type ? "国产车" : "进口车")); } }
调整说明
- 车辆类型改为先读取字符串输入,再根据预设规则转换为布尔值,匹配
national则为true,否则为false - 补充了读取到的属性赋值给Car对象的逻辑,新增了中文类型输出的代码
- 处理了nextDouble后的换行符残留问题,避免后续读取字符串异常
内容的提问来源于stack exchange,提问作者Daniya Puteri
相关产品推荐
相关产品推荐

