Java如何定位金字塔每行最后元素并实现指定文件数据输出
解决方案:定位金字塔每行最后元素并输出键值对
核心逻辑
你需要的金字塔每行最后一个元素,本质是前n个正整数的累加和:
- 第1行最后一个元素:
1 = 1 - 第2行最后一个元素:
3 = 1+2 - 第3行最后一个元素:
6 = 1+2+3
总共有6个元素,计算到累加和为6即可。
修改后的代码
直接计算出目标键(1、3、6),从HashMap中直接取值输出,无需遍历所有entry:
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; public class PyramidLastElement { public static void main(String[] args) throws IOException { HashMap<Integer, String> mapOfInputs = new HashMap<>(); BufferedReader reader; try { reader = new BufferedReader(new FileReader("C:\\temp\\Foo.txt")); String fileLine = reader.readLine(); while (fileLine != null) { // 优化分割逻辑,兼容多位数数字 String[] parts = fileLine.split(" ", 2); int number = Integer.parseInt(parts[0]); mapOfInputs.put(number, parts[1]); fileLine = reader.readLine(); } reader.close(); } catch (IOException fnfEx) { System.out.println("File not found or cannot be read"); } catch (NumberFormatException | ArrayIndexOutOfBoundsException nfEx) { System.out.println("Check your file, not formatted correctly. Expecting -> [Number][Space][Word]"); } // 生成金字塔每行最后一个元素的键并输出 int total = 0; int row = 1; while (total < 6) { total += row; String value = mapOfInputs.get(total); if (value != null) { System.out.println(total + ": " + value); } row++; } } }
代码说明
- 读取文件部分用
split(" ", 2)按空格分割行内容,避免了原代码中substring(0,1)只能处理个位数数字的问题。 - 核心逻辑通过累加行号直接得到每行最后一个元素的键,从HashMap中直接取值输出,逻辑更简洁高效。
- 异常处理补充了
ArrayIndexOutOfBoundsException,覆盖文件行格式错误导致的数组越界场景。
内容的提问来源于stack exchange,提问作者ResourceReaper
相关产品推荐
相关产品推荐

