我正在尝试解析数据文件。该代码已成功用于我的其他数据文件;但是,我现在收到错误。这些数据文件是缩进的,因此计算机尝试读取第一个空格。我如何跳过这个空间?
String line = br.readLine();
while (line != null) {
String[] parts = line.split(" ");
if (linecounter != 0) {
for (int j=0; j<parts.length; j++) {
if (j==parts.length-1)
truepartition.add(Integer.parseInt(parts[j]));
else {
tempvals.add(Double.parseDouble(parts[j]));
numbers.add(Double.parseDouble(parts[j]));
}
}
Points.add(tempvals);
tempvals = new ArrayList<Double>();
} else {
//Initialize variables with values in the first line
// Reads each elements in the text file into the program 1 by 1
for (int i=0; i<parts.length; i++) {
if (i==0)
numofpoints = Integer.parseInt(parts[i]);
else if (i==1)
dim = Integer.parseInt(parts[i]) - 1;
else if (i==2)
numofclus = Integer.parseInt(parts[i]);
}
}
linecounter++;
line = br.readLine();
}
Data File
75 3 4
4 53 0
5 63 0
10 59 0
最佳答案
出现此数字格式错误是因为您无法格式化以 10 为基数的空格字符。 我可以看到您的输入中有许多额外的空格, split("") 这不起作用。
因此用正则表达式替换正常的空格分割。 使用下面的代码,它将处理您输入中的额外空格。
String[] parts = line.trim().split("\\s+");
关于Java 尝试将意图读取为整数字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59127239/