gpt4 book ai didi

java - 读取txt并保存到数组中,java

转载 作者:行者123 更新时间:2023-12-01 14:13:46 26 4
gpt4 key购买 nike

在 java 中读取文件并将每个元素保存到 2 个数组中时遇到一些问题。我的txt是这样的

2,3
5
4
2
3
1

其中第一行是两个数组 A=2 和 B=3 的长度,然后是每个数组的元素。我不知道如何将它们保存到 A 和 B 中并用它们的长度初始化数组。最后每个数组将是 A=[5,4] B=[2,3,1]

public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter

FileInputStream fstream = new FileInputStream("prova.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != " ") {
String[] delims = strLine.split(",");
String m = delims[0];
String n = delims[1];
System.out.println("First word: "+m);
System.out.println("First word: "+n);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}

这是我做的..我使用了System.out.println....只是为了在控制台中打印,这是没有必要的...有人可以帮助我,给我一些建议吗?提前致谢

最佳答案

再次,将大问题分解为小步骤,解决每个步骤。

  1. 阅读第一行。
  2. 解析第一行以获取 2 个数组的大小。
  3. 创建数组。
  4. 循环第一个数组 length 次并填充第一个数组。
  5. 循环第二个数组长度次并填充第二个数组。
  6. 在finally block 中关闭BufferedReader(确保在try block 之前声明它)。
  7. 显示结果。

关于java - 读取txt并保存到数组中,java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18294577/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com