Hi
Im trying to write a program that take list of numbers from TXT file
then save them into array
then convert them into integers and do a binary search on them
here is what i tried to do
import java.util.ArrayList;
import java.util.Collections;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class BinarySearchArrayListExample {
public static void main(String[] args) {
//Read A TXT File
File file = new File("test.txt");
StringBuffer contents = new StringBuffer();
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(file));
String text = null;
// repeat until all lines is read
while ((text = reader.readLine()) != null)
{
contents.append(text)
.append(System.getProperty(
"line.separator"));
}
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
} finally
{
try
{
if (reader != null)
{
reader.close();
}
} catch (IOException e)
{
e.printStackTrace();
}
}
// show file contents here
System.out.println(contents.toString());
//ArraY
ArrayList arrayList = new ArrayList();
//Add elements to Arraylist
arrayList.add(contents.toString());
//First sort an ArrayList using sort method of Collections class
Collections.sort(arrayList);
System.out.println("Sorted ArrayList contains : " + arrayList);
//search an element using binarySearch method of Collections class
int index = Collections.binarySearch(arrayList,"2");
System.out.println("Element found at : " + index);
}
}