【发布时间】:2017-11-13 13:09:15
【问题描述】:
我有这个文本文件,我需要将它提取到 Java 程序中以确定数组大小及其值。我可以单独读取每一行,但无法获取包含许多数字的行的值。另外,如何计算第三行中的元素。(0 2)
4
5
0 2
0 1 0.6
0 2 0.2
0 3 0.5
1 3 0.8
2 3 0.3
我正在使用的这段代码:
List<Integer> list = new ArrayList<Integer>();
File file = new File("D:\\ALGORTHIMS\\MASTER LEVEL\\dr. khaled\\assignment 1\\text.txt");
BufferedReader reader = null;
List<Double> ints = new ArrayList<Double>();
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null) {
if (text.length() == 1) {
list.add(Integer.parseInt(text));
} else {
String[] strs = text.trim().split("\\s+");
for (int i = 0; i < strs.length; i++) {
ints.add(Double.parseDouble(strs[i]));
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}
//print out the list
System.out.println(list);
System.out.println(ints);
【问题讨论】:
-
Integer.parseInt(text)将不起作用,因为文件中有float数字。请使用text.split("\\s+")以空格分隔数字。 -
它不起作用,检查我的更新
标签: java