In the file, each entry will contain two lines; the first line is the number, and the second line is the title. The entries in the file will be in numerical ascending order.
Create a program that reads the a file into an array. The user will then request a title based on the number. Your program will perform a binary search to find the title.
Currently, I read everything from the file into an arrayList, and from there I convert it into an array.
My first major issue is that my binary search method does not appear to be working; I attempt to search for a number, and it simply returns false. Secondly, even if this manages to work, I am unsure of how to record which line in the text file the result was found in. I assume this is necessary, as I must output the line after. This is an example of what the text file looks like.
2
The messianic drama
4
Evening prayer
7
Prayer of the virtuous under persecution
etc. This is my current code
package Psalms;
import java.io.*;
import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
public class Psalms {
public static void main(String[] args) throws IOException {
// Creates array list. Reads lines into it
List<String> psalms = new ArrayList<String>();
BufferedReader readFile = new BufferedReader(new FileReader("Psalms.txt"));
String line;
while ((line = readFile.readLine()) != null) {
psalms.add(line);
}
readFile.close();
String[] psalmArray = new String[psalms.size()];
psalmArray = psalms.toArray(psalmArray);
//Asks user what to search for.
String psalmSearch = (JOptionPane.showInputDialog("What number Psalm would you like to search for?"));
System.out.println("Binary Search: " + psalmSearch + " " + binarySearch(
psalmArray, 0, psalmArray.length - 1, psalmSearch));
}
public static boolean binarySearch(String myArray[], int left,
int right, String searchForPsalm) {
int middle;
if (left > right) {
return false;
}
middle = (left + right) / 2;
if (myArray[middle].equals(searchForPsalm)) {
return true;
}
if (searchForPsalm.compareTo(myArray[middle]) < 0) {
return binarySearch(myArray, left, middle - 1,
searchForPsalm);
} else {
return binarySearch(myArray, middle + 1, right,
searchForPsalm);
}
}
}