求教 求教 ,txt读取 ,然后存入树中. 为什么呢?为什么呢?求解啊~高手们。头疼。
我想将读取一个.txt 中的记录,例如6274 John Johnson 315.56
2843 Mark Wilson 7217.23
4892 Dana Albright 31462.56
将每一行记录,生成一个 Employee 类的 object .
然后将它存入 Binary Search Tree 中...一条一条加入树中。
但是在存入树中时,抛出了一个 NullPointer 异常。
实在不解,为什么?
程序代码:
public class Lab5 { public static void main (String[] args) throws IOException { Company company = new Company(); company.menu("1 - Employees.txt"); } } public class Company { public void menu(String line)throws IOException { String delim = "- \r\t"; String file = ""; int id = 0; String lastName="" , firstName= ""; double salary = 0.0; TreeBag bsTree = null; StringTokenizer tokenizer = new StringTokenizer(line,delim); int command = Integer.parseInt(tokenizer.nextToken()); switch(command) { case 1: //创建一个树,然后将.txt中的记录存入。 while(tokenizer.hasMoreTokens()) { file = tokenizer.nextToken(); } BufferedReader fileIn = new BufferedReader(new FileReader(file)); String record = fileIn.readLine(); while(record != null ) { StringTokenizer tokenizer2 = new StringTokenizer(record); while(tokenizer2.hasMoreTokens()) { id = Integer.parseInt(tokenizer2.nextToken()); lastName = tokenizer2.nextToken(); firstName = tokenizer2.nextToken(); salary = Double.parseDouble(tokenizer2.nextToken()); Employee employee = new Employee(id,lastName,firstName,salary); //System.out.println( employee.tostring()); bsTree.add(employee);//这里抛出nullpointer 异常 } record = fileIn.readLine(); } break; ...... }//end switch }//end main }//end class public class TreeBag { private BTNode root ; public TreeBag() { root = null; } public void add(Comparable element) { addNode(element,root); } public BTNode addNode(Comparable element , BTNode p) { if(p == null) p = new BTNode(element, null ,null); else if((p.getData())<0) p.setLeft(addNode(element,p.getLeft())); else if((p.getData())>0) p.setRight(addNode(element,p.getRight())); else p.setData(element); return p; } }
除此之外,当然有 个class BTNode {...} , 就不列不来了。