Java BMI计算程序问题:如何将函数结果追加写入文件
修复BMI计算程序的问题:返回值与文件追加写入
你的代码存在两个核心问题:计算函数未返回结果、文件写入是覆盖而非追加。以下是修复后的完整代码,以及关键修改点说明:
修复后的完整代码
import java.util.Scanner; import java.io.*; public class BMI { // 公制BMI计算:改为返回double类型结果 static double metric() { Scanner inVal = new Scanner(System.in); System.out.println("Enter your weight, in kilograms: "); double kilograms = inVal.nextDouble(); // 改用nextDouble支持小数输入 System.out.println("Enter your height, in meters: "); double meters = inVal.nextDouble(); double metricbmi = kilograms / (meters * meters); return metricbmi; // 返回计算好的BMI值 } // 英制BMI计算:改为返回double类型结果 static double imperial() { Scanner inVal = new Scanner(System.in); System.out.println("Enter your weight, in pounds: "); double pounds = inVal.nextDouble(); // 改用nextDouble支持小数输入 System.out.println("Enter your height, in inches: "); double inches = inVal.nextDouble(); double imperialbmi = (pounds * 703) / (inches * inches); return imperialbmi; // 返回计算好的BMI值 } public static void main(String[] args) throws IOException { Scanner input = new Scanner(System.in); System.out.println("Enter your name: "); String name = input.nextLine(); System.out.println("Enter 1 to calculate BMI in metric system or 2 for imperial system: "); int system = input.nextInt(); double calculatedBMI = 0; if (system == 1) { calculatedBMI = metric(); // 接收公制计算返回的BMI值 } else if (system == 2) { calculatedBMI = imperial(); // 接收英制计算返回的BMI值 } else { System.out.println("Invalid choice!"); return; // 选择无效时直接退出程序 } // 使用FileWriter的追加模式(第二个参数为true)实现文件内容追加 try (PrintWriter outputFile = new PrintWriter(new FileWriter("BMI.txt", true))) { outputFile.println(name + " BMI is: " + calculatedBMI); System.out.println("Result has been appended to the BMI.txt file!"); } // try-with-resources会自动关闭文件,无需手动调用close() } }
关键修改说明
让计算函数返回结果
- 把
metric()和imperial()的返回类型从void改为double - 在函数末尾添加
return语句,返回计算得到的BMI值 - 主函数中通过变量接收返回值,解决了原代码中无法访问函数内部变量的问题
- 把
实现文件追加写入
- 原代码直接用
PrintWriter("BMI.txt")会覆盖文件原有内容,改用new PrintWriter(new FileWriter("BMI.txt", true)),其中FileWriter的第二个参数true表示追加模式 - 使用
try-with-resources语法,无需手动调用close(),Java会自动处理文件关闭,避免资源泄漏
- 原代码直接用
输入优化
- 把
nextInt()改为nextDouble(),支持小数形式的体重和身高输入(比如身高1.75米) - 移除了多余的
Scanner实例,只用一个input即可处理所有输入
- 把
内容的提问来源于stack exchange,提问作者user23342283
相关产品推荐
相关产品推荐

