简体   繁体   中英

Java Array Index out of Bounds Exception (-1)?

I realise that this question has been asked before, but I was unable to understand much of the answers that I read. I have been working on this code for a while:

  static ArrayList<String> psalmsTitlesArray = new ArrayList<>(47);
    static ArrayList<String> psalmsNumbersArray = new ArrayList<>(47);
    static String psalmTextFileArray[] = new String[47];
    static int index = 0;

    public static void main(String[] args) throws IOException {
        //this program demonstrates a binary array search. It is going to search
        //the text file "Psalms.txt" for a number list of the pslams.
        // eg. the user wants to see psalm 7
        // the program will display "prayer of the virtuous under persecution".
        BufferedReader fileRead = new BufferedReader(new FileReader("Psalms.txt")); //create a BufferedReader to read the file
        String fileLine = "";
        int lineNumber = 1;
        for (int i = 0; i < 47; i++) {
            fileLine = fileRead.readLine(); // stores each line of text in a String 
            if (fileLine == null) { //if the line is blank
                break; // don't read it
            }
            psalmTextFileArray[i] += fileLine;
            if (lineNumber % 2 == 0) { //if the line is not an even number 
                psalmsTitlesArray.add(fileLine); //add the line to the Titles array
                lineNumber++;
            } else { //otherwise,
                psalmsNumbersArray.add(fileLine); //add it to the numbers array
                lineNumber++;
            }
        }
        String userInput = JOptionPane.showInputDialog(null, "What psalm would you like me to search for?", "Psalm Finder",
                JOptionPane.QUESTION_MESSAGE);
        if (userInput == null) {
            System.exit(0);
        }
        int numberInput = Integer.parseInt(userInput);

        binarySearch(psalmsNumbersArray, 0, (psalmsNumbersArray.size() - 1), userInput);
        for (int i = 0; i < psalmTextFileArray.length; i++) {
        index = psalmTextFileArray[i].indexOf(numberInput);
        }
        JOptionPane.showMessageDialog(null, "I found Psalm #" + userInput + ". It is: \n" + psalmTextFileArray[index]);

    }

    public static boolean binarySearch(ArrayList<String> myPsalmsArray, int left, int right, String searchForPsalm) {
        int middle;
        if (left > right) {
            return false;
        }
        middle = (left + right) / 2;
        if (myPsalmsArray.get(middle).equals(searchForPsalm)) {
            return true;
        }
        if (searchForPsalm.compareTo(myPsalmsArray.get(middle)) < 0) {
            return binarySearch(myPsalmsArray, left, middle - 1,
                    searchForPsalm);
        } else {
            return binarySearch(myPsalmsArray, middle + 1, right,
                    searchForPsalm);
        }
    }
}

This code reads from the file "Psalm.txt". Essentially, the Pslams are in order from 1 - 99 (but not every Psalm is included, for example, pslam 4 does not exist within the text file)

I am attempting to use the indexOf() to find at what index a character first appears. Then, I will be able to move it forward one index in the array and find the title, as the information in the array is listed like:

[2, psalm 2 title, 3, psalm 3 title, 4...] (etc)

This is the small chunk of code that appears to be causing the issue:

for (int i = 0; i < psalmTextFileArray.length; i++) {
            index = psalmTextFileArray[i].indexOf(numberInput);
            }
            JOptionPane.showMessageDialog(null, "I found Psalm #" + userInput + ". It is: \n" + psalmTextFileArray[index]);

So, if I could find the index of 2 in the array, move it forward one index, I would have the title. Also, the index is consistently throwing a -1 exception. What does this mean?

Apologies if this is confusing, I can clarify anything that is unclear (I'll try my best!)

You are getting exception because of Your code is not valid

 int numberInput = Integer.parseInt(userInput);

    binarySearch(psalmsNumbersArray, 0, (psalmsNumbersArray.size() - 1), userInput);
    for (int i = 0; i < psalmTextFileArray.length; i++) {
    index = psalmTextFileArray[i].indexOf(numberInput);
    }
    JOptionPane.showMessageDialog(null, "I found Psalm #" + userInput + ". It is: \n" + psalmTextFileArray[index]);

in above code psalmTextFileArray[i] will return one String object. then you are doing indexOf(numberInput)

as mentioned in JavaDoc

the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.

so if your numberInput is not in String object your index will become -1 as

index = -1

and in next line when you are calling showMessageDialog you are accessing array's position with -1 as you are using psalmTextFileArray[index] so you are getting ArrayIndexOutOfBoundsException

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM