Java读取TXT文件时仅读取数字首列问题求助
解决读取txt文件到姓名数组和分数二维数组的问题
嘿,我来帮你捋捋这个问题!从你描述的情况来看,问题肯定出在读取数字的逻辑上——你应该是只取了每个姓名后的第一个数字,没把后续的所有分数都塞进二维数组里。
首先,先明确你的文件结构:所有数据都是用空格(或换行)分隔的,每一组是「姓名 + N个整数分数」,比如Jason 10 15 20...之后跟着下一个姓名和分数。这种情况下,不能按行读取后简单拆分,因为可能一个人的数据跨了多行,或者多个姓名在同一行。
核心思路
- 先把整个文件的内容拆分成单个的字符串元素(不管是空格还是换行,都当成分隔符),去掉空元素;
- 用一个指针遍历这些元素:遇到非数字的就作为姓名存入一维数组,接着循环读取后续的所有数字,直到遇到下一个非数字(也就是下一个姓名),把这组数字存入二维数组的对应行。
代码示例(以C#为例)
using System; using System.Collections.Generic; using System.IO; using System.Linq; class Program { static void Main() { // 读取文件所有内容,分割成单个元素(去掉空元素) var allData = File.ReadAllText("your_file.txt") .Split(new[] {' ', '\n', '\r'}, StringSplitOptions.RemoveEmptyEntries); // 用List暂存数据(比直接用数组更灵活,不用提前算长度) List<string> namesList = new List<string>(); List<List<int>> scoresList = new List<List<int>>(); int currentIndex = 0; while (currentIndex < allData.Length) { // 读取当前姓名 namesList.Add(allData[currentIndex]); currentIndex++; // 收集当前姓名对应的所有分数 List<int> currentScores = new List<int>(); while (currentIndex < allData.Length && int.TryParse(allData[currentIndex], out int score)) { currentScores.Add(score); currentIndex++; } scoresList.Add(currentScores); } // 转成你需要的数组格式 string[] NamesArray = namesList.ToArray(); int[][] ScoresArray = scoresList.Select(scoreList => scoreList.ToArray()).ToArray(); // 测试输出验证 for (int i = 0; i < NamesArray.Length; i++) { Console.WriteLine($"姓名: {NamesArray[i]} 分数: {string.Join(" ", ScoresArray[i])}"); } } }
为什么你的代码只读取了第一列数字?
大概率是这几个原因:
- 你可能用了逐行读取,然后每行只拆分出第一个数字,没处理后续的;
- 二维数组的列数被你固定成了1,或者循环读取数字的逻辑只执行了一次;
- 没有正确区分姓名和数字的边界,读完一个姓名后只取了下一个元素就跳到下一个姓名了。
如果你用Java的话,类似逻辑的代码示例
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; public class DataReader { public static void main(String[] args) throws IOException { String content = new String(Files.readAllBytes(Paths.get("your_file.txt"))); // 分割所有空白字符(空格、换行、制表符等) String[] allData = content.split("\\s+"); List<String> namesList = new ArrayList<>(); List<List<Integer>> scoresList = new ArrayList<>(); int index = 0; while (index < allData.length) { // 添加姓名 namesList.add(allData[index]); index++; List<Integer> currentScores = new ArrayList<>(); // 循环读取数字直到遇到非数字 while (index < allData.length) { try { int score = Integer.parseInt(allData[index]); currentScores.add(score); index++; } catch (NumberFormatException e) { // 遇到非数字,退出循环处理下一个姓名 break; } } scoresList.add(currentScores); } // 转成数组 String[] namesArray = namesList.toArray(new String[0]); int[][] scoresArray = new int[scoresList.size()][]; for (int i = 0; i < scoresList.size(); i++) { scoresArray[i] = scoresList.get(i).stream().mapToInt(Integer::intValue).toArray(); } // 验证输出 for (int i = 0; i < namesArray.length; i++) { System.out.print(namesArray[i] + ": "); for (int score : scoresArray[i]) { System.out.print(score + " "); } System.out.println(); } } }
内容的提问来源于stack exchange,提问作者TM1
相关产品推荐
相关产品推荐

