gpt4 book ai didi

java - 字符串索引超出范围 : -1

转载 作者:行者123 更新时间:2023-11-29 03:57:34 26 4
gpt4 key购买 nike

我有一个类似的问题。这是我的来源的片段:

FileWriter fstream = new FileWriter("results_for_excel.txt");
BufferedWriter writer = new BufferedWriter(fstream);
String sourceDirectory = "CVs";
File f = new File(sourceDirectory);
String[] filenames = f.list();
Arrays.sort(filenames);
String[] res = new String[filenames.length];
for (int i = 0; i < filenames.length; i++) {
System.out.println((i + 1) + " " + filenames[i]);
}


for (int i = 0; i < filenames.length; i++) {
int beg = filenames[i].indexOf("-");
int end = filenames[i].indexOf(".");
res[i] = filenames[i].substring(beg,end);
System.out.println((i+1)+res[i]);
writer.write(res[i] + "\n");
}
writer.flush();
writer.close();

我在 res[i] = filenames[i].substring(beg,end) 处遇到异常;我不知道发生了什么事。提前致谢:)P.S 我已经阅读了所有重复的内容,但什么也没发生:(

最佳答案

之后添加如下代码
int beg = filenames[i].indexOf("-");
int end = filenames[i].indexOf(".");

这将显示格式错误的文件名;

if (beg == -1 || end == -1)
{
System.out.println("Bad filename: " + filenames[i]);
}

关于java - 字符串索引超出范围 : -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5448851/

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