Java新手编写薪资计算方法调用程序出现InputMismatchException报错求助
问题排查及修复方案
你的代码存在3个核心问题,按影响优先级排序如下:
- 输入类型不匹配(触发当前报错的直接原因)
任务要求读取三个浮点数,但代码中所有输入读取方法均使用nextInt()读取整数,当输入为小数(例如15.5小时、89.2时薪)时,就会直接抛出InputMismatchException异常。同时三个输入方法的返回值均为int类型,也不符合浮点数的业务要求。 - 提示文案错误
askTaxPercent()方法的提示语错误打印为「Type in the number of work hours: 」,会误导用户重复输入工作时长,无法采集到正确的税率值。 countTaxlessSalary方法逻辑错误
该方法的定位是计算税前薪资,正确逻辑应为工作时长 × 时薪,但现有方法内部定义了值为0的局部税率变量,额外做了扣税计算,返回值和方法预期功能不符,还会和主方法后续的计税逻辑冲突。
修复后的完整代码
import java.util.Scanner; public class SalaryCountingWithMethods { static Scanner reader = new Scanner(System.in); public static void main (String [] args) { double hours, salaryPerHour, taxPercent, taxlessSalary, taxPart; hours = askHours(); salaryPerHour = askSalaryPerHour(); taxPercent = askTaxPercent(); taxlessSalary = countTaxlessSalary(hours, salaryPerHour); taxPart = taxlessSalary * taxPercent / 100; System.out.println("\nSalary before taxes: " + taxlessSalary); System.out.println("Tax part of the salary: " + taxPart); System.out.println("Salary after taxes: " + (taxlessSalary - taxPart)); } private static double askHours(){ System.out.print("Type in the number of work hours: "); return reader.nextDouble(); } private static double askSalaryPerHour(){ System.out.print("Type in salary per hour: "); return reader.nextDouble(); } public static double askTaxPercent(){ System.out.print("Type in the tax percent: "); return reader.nextDouble(); } private static double countTaxlessSalary(double hours, double salaryPerHour){ return hours * salaryPerHour; } }
修复说明
- 所有输入读取的
nextInt()替换为nextDouble(),输入方法返回值统一调整为double,匹配浮点数输入要求 - 修正
askTaxPercent()的提示文案为税率采集相关内容 - 简化
countTaxlessSalary逻辑,直接返回税前薪资的计算结果,和方法功能定位对齐 - 移除不必要的float强制类型转换,避免精度损失
内容的提问来源于stack exchange,提问作者Arzidal
相关产品推荐
相关产品推荐

