gpt4 book ai didi

Java StringIndexOutOfBoundsException

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

我正在编写一个程序,该程序从文件“items.txt”获取输入,并根据“changes.txt”添加或删除行,然后输出到另一个文件。

这是“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"

这是我的方法,有问题(voidchanges() 是第 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

我在打印语句中添加了“添加”和“完成”只是为了帮助尽早诊断问题。即使它打印“add”和“done”,也不会发送任何内容到输出文件。我猜这是由于 StringIndexOutOfBoundsException 造成的

这是我在 Stack Overflow 上的第一个问题,因此请对任何格式问题或不当礼仪保持耐心。

最佳答案

原因是您使用 ",|\r|\n" 作为分隔符。这将返回换行符的 \r\n 之间的空标记(假设您使用的是 Windows 样式的换行符)。例如:

Scanner sc = new Scanner(new StringReader("Hello\r\nWorld"));
sc.useDelimiter(",|\r|\n");
while (sc.hasNext()) {
String n = sc.next();
System.out.println(n.length() + " " + n);
}

输出:

5 Hello
0
5 World

Ideone demo

因此,对于那些零长度标记,您无法读取 charAt(0),因为没有这样的字符。

将分隔符更改为 ",|\r\n" 之类的内容,即将 \r\n 视为单个分隔符。

关于Java StringIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42590114/

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