user3822332
user3822332

Reputation: 219

Manual array sort returning nullpointerexception

Anyone have any idea why this code is returning a nullpointerexception? It's supposed to sort an array alphabetically, but it's not performing that function.

public void borrowerSort() throws IOException {
        String inputFile = "Borrower Details.txt";
        String outputFile = "Borrower Details2.txt";

        FileReader txtArranger = new FileReader(inputFile);
        BufferedReader txtReader = new BufferedReader(txtArranger);



        for(int i = 0; i <= inputFile.length(); i ++)
        {
            borrowerDetails[i] = txtReader.readLine();
//      
//          System.out.println(borrowerDetails[i]);
//      System.out.println();
        }

        //System.out.println(borrowerDetails[0] + borrowerDetails[2]);
        for(int j = 0; j < borrowerDetails.length - 1; j ++)
        {
            for(int k = j + 1; k < borrowerDetails.length; k ++)
            {
                if(borrowerDetails[j].compareTo(borrowerDetails[k]) > 0){
                    String store = borrowerDetails[j];
                    borrowerDetails[j] = borrowerDetails[k];
                    borrowerDetails[k] = store;

                }

            }
        }

Upvotes: 1

Views: 94

Answers (2)

Battle_Slug
Battle_Slug

Reputation: 2105

It seems you have fixed-size array of objects borrowerDetails, while your input txt files doesn't guarantee that this array is filled completely. Empty array of objects is initialized with nulls, so if you don't fill it completely, you finally end up trying to do something like object.lenght > null that causes NPE. Please try to trace and check how completely it is being filled with borrowerDetails[i] = txtReader.readLine(); cycle.

Upvotes: 0

laune
laune

Reputation: 31290

    String inputFile = "Borrower Details.txt";

    for(int i = 0; i <= inputFile.length(); i ++)
    {
        borrowerDetails[i] = txtReader.readLine();

It is not possible to derive the size of a file in lines from the length of the name of the file.

Use a List<String> to read the lines, copy to an array and sort that.

List<String> lines = new ArrayList<>();
String line;
while( (line = txtReader.readLine()) != null ){
    lines.add( line );
}

The reason for the NPE is due to the incorrect allocation for String[] borrowerDetails. If this array is longer than the number of lines (!) in the file, some array elements remain null, which causes NPE when borrowerDetails[j].compareTo(...) is called

Upvotes: 4

Related Questions