[英]Null pointer exception when bubble sorting a 2D array
我的代码正在读取txt文件,然后根据用户指定的字段对其进行排序,然后将其输出到表上。 这是代码:
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
。 因此,第一次尝试读取和解析行(在第二个循环中)将返回null
并且永远不会执行解析循环的主体。
您可以关闭然后重新打开文件,尝试在i
上使用mark()
和reset()
,或者(最好)将其读入ArrayList<String[]>
而不是对文件进行两次遍历。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.