0

I am making a movie rental program and I need to write an array of Strings into an ArrayList of Movie Objects. Everything compiles correctly, but when it is run I get a String index out of bounds error. Here is the code for the methods used:

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;
}

The getIndex() method gets the index of a semicolon inserted between the title and number of copies of the movie so when it is read from an external file the two can be distiguished and then used as parameters to create a Movie object.

Any thoughts on why I am getting an index out of bounds error?

Here is the complete error message:

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)

2 Answers 2

1

If the length of the second parameter of substring method is less than the first parameter, the length of new index will be negative and its value will be thrown in StringIndexOutOfBoundsException.

Sign up to request clarification or add additional context in comments.

Comments

0

You are getting a StringIndexOutOfBoundsException, that means that the String you are operating on an empty string and the index value returned is 0 (as you set the default index value to 0 in getIndex method). When you call the below statement it is throwing error

title = array[i].substring(0,index + 1);

before calling the getIndex method, make sure you check whether string is not null and not empty

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.