我正在制作一个电影租赁程序,我需要将一个字符串数组写入电影对象的 ArrayList 中。一切都正确编译,但是当它运行时,我收到字符串索引越界错误。以下是所使用方法的代码:
public static void arrayToList(Store store, String[] array)
{
String title;
int copies;
int index = -1;
for(int i = 0;i < array.length;i++)
{
index = getIndex(array[i]);
title = array[i].substring(0,index + 1);
copies = Integer.parseInt(array[i].substring(index+1,array[i].length()));
store.addMovie(title,copies);//adds movie to arrayList
}
}
public static int getIndex(String line)
{
boolean found = false;
int index =0;
for(int i = 0;i < line.length();i++)
{
if(line.charAt(i) == ';')
{
index = i;
}
}
return index;
}
getIndex() 方法获取插入在电影标题和份数之间的分号索引,因此当从外部文件读取时,可以区分两者,然后将其用作创建 Movie 对象的参数。
对于为什么我收到索引越界错误有什么想法吗?
以下是完整的错误消息:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.substring(String.java:1950)
at MovieRentals.MovieRunner.arrayToList(MovieRunner.java:158)
at MovieRentals.MovieRunner.main(MovieRunner.java:32)
最佳答案
如果 substring 方法的第二个参数的长度小于第一个参数,则新索引的长度将为负数,并且其值将抛出 StringIndexOutOfBoundsException。
关于java - 线程中的异常 "main"java.lang.StringIndexOutOfBoundsException : String index out of range: 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29810900/