我意識到這個問題之前已經被問到過,但我無法理解我讀到的很多答案。我一直在這個代碼了一會兒:Java數組索引溢出異常(-1)?
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);
}
}
}
此代碼從文件「Psalm.txt」匾額。本質上,Pslams從1 - 99的順序(但不是每個詩篇都包含在內,例如,文本文件中不存在pslam 4)
我試圖使用indexOf()來查找哪個索引首先出現一個角色。然後,我將能夠將其向前移動到數組中的一個索引並找到標題,因爲數組中的信息如下所列:
[2,psalm 2 title,3,psalm 3 title,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]);
所以,如果我可以在陣列中找到的2的指數,其向前推進的一個索引,我會有標題。 此外,索引始終引發-1異常。這是什麼意思?
道歉,如果這是混亂的,我可以澄清任何不清楚(我會盡我所能!)