简体   繁体   中英

Null pointer exception when bubble sorting a 2D array

My code is reading through a txt file and then sorting it according to a field specified by the user and then outputting it on a table. Here's the code:

public static void sortByAtomicNumber() throws IOException
{
    File file = new File("Elements.txt");
    FileReader reader = new FileReader(file);
    BufferedReader i = new BufferedReader(reader);

    int lines = 0;
    while (i.readLine() != null) {
        lines++;
    }

    String[][] s = new String[lines][];
    String line;
    int index = 0;

    DefaultTableModel model = new DefaultTableModel(                                                                                      //Builds the table model
            new Object[]{"Name","Symbol","Atomic Number","Atomic Mass", "# of Valence Electrons"},
            0);

    while ((line = i.readLine()) != null && index < 10)
        s[index++] = line.split(",");

    for (int x = 0; x < s.length; x++)
    {
        for (int j = x + 1; j < s.length; ++j)
        {
            if (Integer.parseInt(s[x][2])>(Integer.parseInt(s[j][2])))
            {

                String[] temp = s[x];
                s[x] = s[j];
                s[j] = temp;
            }
        }
    }

    for(int x=0;x<s.length;++x){
        Object[]rows = {s[x][0], s[x][1], s[x][2], s[x][3], s[x][4]};                  //Puts information about the sorted elements into rows                                  
        model.addRow(rows);

    }
    JTable table = new JTable(model);                                                        
    JOptionPane.showMessageDialog(null, new JScrollPane(table));                           //Displays the table

}

Getting a java.lang.NullPointerException on this line when I run the program:

if (Integer.parseInt(s[x][2])>(Integer.parseInt(s[j][2])))

This is the data that is it searching through: http://i.imgur.com/LCBA2NP.png

Not sure why this is happening, can anybody help me out?

You are not actually reading the data into the array s . The problem is that in the process of counting lines, you have read to the end of the file and you are not resetting i back to the beginning. Thus every element of s is null . Thus the first attempt to read and parse a line (in the second loop) returns null and the body of the parsing loop is never executed.

You can either close and reopen the file, try using mark() and reset() on i , or (best) read into an ArrayList<String[]> instead of doing a two-pass read of the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM