gpt4 book ai didi

Java hashmap 与自己制作的盒子?

转载 作者:行者123 更新时间:2023-12-01 13:17:21 25 4
gpt4 key购买 nike

我在运行代码时遇到问题。它旨在从包含数据的文件中实现框的映射。我首先输入盒子的名称和重量,然后在该程序中运行另一个程序,添加盒子之间的关系。

文件示例:

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)

有什么想法吗?

最佳答案

您没有在 Box 类中初始化 topbottom,因此 Java 为它们提供了默认值 null.

初始化它们。

public Box(String name, int Size){
this.setName(name);
this.setSize(Size);
top = new ArrayList<Box>();
bottom = new ArrayList<Box>();
}

关于Java hashmap 与自己制作的盒子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22360886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com