Android Studio实现文本数组减Lehmer均值并格式化输出到文件
解决方案
步骤1:将读取的文本值存入double数组
原代码仅将数据拼接为字符串,未实际存入数组。需在读取时把每个数值转为double并存储,再转为数组:
public void processPress(View view) throws IOException { EditText fileInputField = findViewById(R.id.editFileName); String fileName = fileInputField.getText().toString(); Scanner sc = new Scanner(new InputStreamReader(getAssets().open(fileName), StandardCharsets.UTF_8)); // 用List动态存储读取的数值 List<Double> valueList = new ArrayList<>(); StringBuilder sb = new StringBuilder(); while (sc.hasNext()) { String numStr = sc.next(); try { double num = Double.parseDouble(numStr); valueList.add(num); sb.append("\n").append(num); } catch (NumberFormatException e) { // 处理非数值内容,可选跳过或标记无效 sb.append("\n[无效数值:").append(numStr).append("]"); } } sc.close(); // 关闭Scanner释放资源 // 转换为double数组 double[] values = new double[valueList.size()]; for (int i = 0; i < valueList.size(); i++) { values[i] = valueList.get(i); } TextView displayAreaTextView = findViewById(R.id.txtResult); displayAreaTextView.setText(sb.toString()); // 执行Lehmer均值计算与文件输出 if (values.length > 0) { shift_lehmer3_mean(values, values.length); writeValuesToFile(values); } }
步骤2:修正Lehmer均值计算逻辑
原方法循环条件完全写反,且未处理边界情况,修正后代码:
public void shift_lehmer3_mean(double[] a, int num_vals) { if (num_vals == 0) return; // 空数组直接返回 int tracker = 0; double squareSum = 0; double cubeSum = 0; // 遍历所有元素计算平方和、立方和 while (tracker < num_vals) { squareSum += Math.pow(a[tracker], 2); cubeSum += Math.pow(a[tracker], 3); tracker++; // 必须自增,避免死循环 } // 避免除以0的异常 if (squareSum == 0) { Arrays.fill(a, 0); return; } double lehmer = cubeSum / squareSum; int timer = 0; // 遍历计算每个数值减去Lehmer均值后的结果 while (timer < num_vals) { double shiftValue = a[timer] - lehmer; a[timer] = shiftValue; timer++; // 自增避免死循环 } }
步骤3:按格式输出到文件
新增方法实现每行一个数值、保留四位小数的文件写入:
private void writeValuesToFile(double[] values) throws IOException { File outfile = new File(getExternalFilesDir(null), "out.txt"); // 使用try-with-resources自动关闭流,防止资源泄漏 try (PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(outfile)))) { DecimalFormat df = new DecimalFormat("#.####"); df.setRoundingMode(RoundingMode.HALF_UP); // 四舍五入规则 for (double val : values) { pw.println(df.format(val)); } } }
关键注意事项
- 资源管理:用try-with-resources语法自动关闭文件流,避免资源泄漏。
- 异常防护:添加了数值解析异常、除以0的处理,防止程序崩溃。
- 循环逻辑:修正了原代码中循环条件写反、未自增导致的死循环问题。
内容的提问来源于stack exchange,提问作者Void Boi
相关产品推荐
相关产品推荐

