找到你要的答案

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

Q:java数组索引越界异常(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!)

我意识到这个问题以前被问过,但是我无法理解我读到的答案。我一直在这个代码工作了一会儿:

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

这个代码从文件中读取“诗篇。txt”。从本质上讲,这pslams是为了从1 - 99(但不是所有的诗篇是包括,例如,pslam 4不存在于文本文件)

我试图用indexof()在什么指数找到第一次出现的字符。然后,我将能够向前移动数组中的一个索引并找到标题,因为数组中的信息被列出:

【2,诗篇2篇标题,3,诗篇3标题,4……)

这是导致这一问题的一小部分代码:

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?

道歉,如果这是混乱,我可以澄清任何不清楚(我会尽力!)

answer1: 回答1:

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

由于代码无效,您将得到异常

 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]);

在上面的代码psalmtextfilearray [我]将返回一个字符串对象。然后你做指标(NumberInput)

如上所述,在JavaDoc

由该对象表示的字符序列中字符的第一次出现的索引,或如果字符不发生,则为1。

所以如果你不在你NumberInput字符串对象的指标将成为1

索引= 1

与线下当你调用showmessagedialog你访问数组的位置- 1为您使用的是psalmtextfilearray [索引]所以你得到对象的大小时抛出

java  arrays  indexoutofboundsexception