gpt4 book ai didi

java - 标记化数组中的空白空间

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

我正在编写一个 Java 程序,它接受一个文本文件,将其分割为空格和 >,然后通过 Integer.parseInt() 操作数字> 和 Double.parseDouble()

但是,每当我尝试运行我的程序时,我都会收到 NumberFormatException 因为显然我的程序正在为标记拾取空白空间。下面是我的代码、文本文件和错误。

代码:

try {
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine()){
String line = scanner.nextLine();
String[] tokens = line.split(" |>");

State s = new State(Integer.parseInt(tokens[1]), 0,
Double.parseDouble(tokens[0]), null);
states.put(s.state, s);

for(int i = 3; i < tokens.length; i++) {
if(tokens[i + 2] == null || tokens[i] == "")
break;
else
edges.add(new Edge(Integer.parseInt(tokens[i]),
Double.parseDouble(tokens[i + 1])));

}
}
scanner.close();
} catch (FileNotFoundException e) {
System.err.println("Error: file could not be found");
}

要解析的文本文件:

1 0 > 1 6 2 6 3 6
1 1 > 4 -1
1 2 > 8 -1
1 3 > 9 -1
1 4 > 1 -1 5 -1 6 -1
1 5 >
1 6 > 7 -1 8 -1
1 7 >
1 8 > 7 -1
0 9 >

错误消息:

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at csu.mcdonald.ASrch.main(ASrch.java:33)

最佳答案

我尝试执行你的程序。我注意到通过拆分变量“line”来获取字符串数组将产生一个数组

[1, 0, , , 1, 6, 2, 6, 3, 6]

这就是为什么这条线

edges.add(new Edge(Integer.parseInt(tokens[i]), 
Double.parseDouble(tokens[i + 1])));

抛出异常。

这里 tokens[i] 是一个空字符串,会抛出 NumberFormatException

请检查你的逻辑。

关于java - 标记化数组中的空白空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26332790/

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