【发布时间】:2013-08-18 00:24:53
【问题描述】:
在 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....只是在控制台中打印没有必要...有人可以帮助我,给我一些建议吗? 提前谢谢
【问题讨论】:
-
Don't compare strings with
==or!=改为使用equals()方法。 -
@Pshemo:是的,我在发布此消息后看到了。他甚至不应该对此进行检查,也不应该在他的代码中使用 while 循环,而应该使用 for 循环,因为他会知道他应该在循环之前循环多少次。
-
致原发帖人:解决大多数编程问题的关键是将大问题分解为小步骤,然后尝试一次解决每个小步骤。同样,您的代码根本不应包含任何 while 循环,而应包含 for 循环,因为您将知道要在每个循环 before 循环多少次。您还需要在 finally 块中关闭 BufferedReader。
标签: java bufferedreader