Java试图将意图读取为整数字符串
我正在尝试解析数据文件中的数据。此代码已成功用于我的其他数据文件;然而,我现在得到一个错误。这些数据文件缩进,因此计算机试图读取第一个空格。我如何跳过这个空间Java试图将意图读取为整数字符串,java,Java,我正在尝试解析数据文件中的数据。此代码已成功用于我的其他数据文件;然而,我现在得到一个错误。这些数据文件缩进,因此计算机试图读取第一个空格。我如何跳过这个空间 String line = br.readLine(); while (line != null) { String[] parts = line.split(" "); if (linecounter != 0) { for (int j=0; j<parts.length; j++) {
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();
}
由于无法格式化以10为基数的空格字符,因此将出现此数字格式错误。 我可以看到在您的输入中有许多额外的空格,split(“”)这将不起作用 所以用正则表达式替换普通的空白分割。 使用下面的代码,它将处理输入中的额外空格
String[] parts = line.trim().split("\\s+");
你考虑过使用这个课程吗。跳过空格并帮助解析文件 例如:
try {
Scanner inp = new Scanner(new File("path/to/dataFile"));
while(inp.hasNext()) {
int value = inp.nextInt();
System.out.println(value);
}
inp.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
使用你的调试器!什么错误?显示其堆栈跟踪!预期输出是什么=?线程“main”java.lang.NumberFormatException中的异常:对于输入字符串:“java.lang.NumberFormatException.forInputString(未知源)在java.lang.Integer.parseInt(未知源)在java.lang.Integer.parseInt(未知源)在phase1.phase4.FileRead(phase4.java:240)在phase1.phase4.main(phase4.java:121)你是说缩进?
try {
Scanner inp = new Scanner(new File("path/to/dataFile"));
while(inp.hasNext()) {
int value = inp.nextInt();
System.out.println(value);
}
inp.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}