0
我在运行我的代码时遇到问题。它旨在通过包含数据的文件实现框图。我首先把盒子的名称和重量放在一起,然后在该程序中运行另一个程序,增加了盒子之间的关系。文件的带有自己制造的盒子的Java哈希映射?
例子:
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();
}
}
}
我也是在另一个类中指定的盒子:
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)
有什么想法?
但是,如果我这样做,我不会能够在一个程序中添加名称和大小,另一个程序中的顶部和底部? – user3412163
这将解决你的NPE。但我不明白你的意见。什么其他程序?我看到一个课程和一些课程。无论是在构造函数中,还是在Salah所做的声明中,初始化都可以工作。 – rgettman
我在声明部分添加了Salah的代码。我的意思是,当我放入时,我的addData程序会出现问题: – user3412163