我在运行代码时遇到问题。它旨在从包含数据的文件中实现框的映射。我首先输入了盒子和重量的名称,然后在该程序中运行另一个程序,它增加了盒子之间的关系。
文件示例:
5
a 2
b 1
c 1
d 3
e 2
3
a b
a d
b c
代码:
package myutil;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Scanner;
public class MyReader {
public MyReader() {
}
public static void addData(String currentFile, HashMap<String, Box> oordnadMap) throws FileNotFoundException{
File file = new File (currentFile);
Scanner scanner = new Scanner (file);
int iterator = Integer.parseInt(scanner.nextLine());
for(int i = 1; i <= iterator; i++){
Box temp = new Box(scanner.next(), Integer.parseInt(scanner.next()));
System.out.println(temp.getName());
System.out.println(temp.getSize());
oordnadMap.put(temp.getName(), temp);
}
addRelation(oordnadMap, scanner);
}
public static void addRelation(HashMap<String, Box> oordnadMap, Scanner scanner)throws FileNotFoundException{
int numerOfRelations = scanner.nextInt();
System.out.println(numerOfRelations);
for (int i = 1; i <= numerOfRelations; i++){
String left =scanner.next();
String right = scanner.next();
Box Box1 = oordnadMap.get(left);
Box Box2 = oordnadMap.get(right);
System.out.println(Box1);
System.out.println(Box2);
Box2.setTop(Box1);
Box1.setBottom(Box2);
}
}
public static void main (String[] args){
HashMap<String, Box> oordnadMap = new HashMap<String,Box> ();
try {
String currentFile="boxes1.txt";
addData(currentFile, oordnadMap );
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我还在另一个类中指定了Box:
package myutil;
import java.util.ArrayList;
public class Box {
private String name;
private int Size;
ArrayList<Box> top;
ArrayList<Box> bottom;
public Box(String name, int Size){
this.setName(name);
this.setSize(Size);
}
public void RemoveBox(String name, int Size){
}
public void setName(String name) {
this.name = name;
}
public void setSize(int size) {
Size = size;
}
public void setTop (Box temp){
this.top.add(temp);
}
public void setBottom (Box temp){
this.bottom.add(temp);
}
public String getName() {
return name;
}
public int getSize() {
return Size;
}
}
当我运行它时,我收到错误:
Exception in thread "main" java.lang.NullPointerException
at myutil.Box.setTop(Box.java:33)
at myutil.MyReader.addRelation(MyReader.java:44)
at myutil.MyReader.addData(MyReader.java:27)
at myutil.MyReader.main(MyReader.java:55)
有什么想法吗?
答案 0 :(得分:1)
您未在top
课程中初始化bottom
或Box
,因此Java为其提供了默认值null
。
初始化它们。
public Box(String name, int Size){
this.setName(name);
this.setSize(Size);
top = new ArrayList<Box>();
bottom = new ArrayList<Box>();
}