我写一个程序,它根据“changes.txt”,并输出到另一个文件需要输入从文件“items.txt”和添加或删除行。爪哇的StringIndexOutOfBoundsException
这是 “items.txt” 文件:
101,Nail #1
102,Nail #2
103,Nail #3
104,Hammer Small
105,Hammer Large
这是更改文件:
A,106,Chainsaw 12"
D,102
d,104
a,107,Chainsaw 10"
这是我的方法,该方法具有的问题(void changes()
是行号132):
void changes() {
try {
fileChange = new Scanner(new File("changes.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
fileChange.useDelimiter(",|\r|\n");
while (fileChange.hasNext()) {
String codeStr = fileChange.next();
if ((codeStr.charAt(0) == 'D') || (codeStr.charAt(0) == 'd')) {
delete(fileChange.nextInt());
System.out.println("delete");
} else if ((codeStr.charAt(0) == 'A') || (codeStr.charAt(0) == 'a')) {
add(fileChange.nextInt(), fileChange.next());
System.out.println("add");
} //else
System.out.println("done");
}
fileChange.close();
}
这是输出我得到:
add
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
done
我在打印语句增加了“添加”和“完成”只是为了帮助在早期诊断问题。即使它打印“添加”和“完成”,也不会将任何内容发送到输出文件。我猜这是由于StringIndexOutOfBoundsException
这是我的第一个关于堆栈溢出的问题,所以请耐心等待任何格式问题或不当礼节。
使用调试器,单步执行代码。看看它在崩溃时使用的值。 – Robert
稍后的一些迭代可能会引发异常。 (Sry,我现在喝醉了。)哪一行会抛出异常? –
您可能会尝试检查空输入的第一个字母(根本没有字母)。 – Robert