对二维数组进行冒泡排序时出现空指针异常

Null pointer exception when bubble sorting a 2D array

我的代码正在读取一个 txt 文件,然后根据用户指定的字段对其进行排序,然后在 table 上输出。这是代码:

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

}

当我 运行 程序时在这一行上得到一个 java.lang.NullPointerException:

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

这是它正在搜索的数据: http://i.imgur.com/LCBA2NP.png

不知道为什么会这样,有人可以帮我吗?

您实际上并未将数据读入数组 s。问题是在计算行数的过程中,您已经读到了文件的末尾,并且没有将 i 重置回开头。因此 s 的每个元素都是 null。因此,第一次尝试读取和解析一行(在第二个循环中)returns null 并且永远不会执行解析循环的主体。

您可以关闭并重新打开文件,尝试在 i 上使用 mark()reset(),或者(最好)读入 ArrayList<String[]> 而不是执行两次读取文件。