例如,我有这段代码。
public class BST{
private Node root;
private double[] start;
public class Node{
private double[] coords;
private String address;
private Node left, right;
private double distance;
public Node (double[] coords, String address){
this.coords = coords; this.address = address;
this.distance = distance(coords);
}
//calculates
public double distance(double[] destination){
double tempLat = start[1] - destination[1];
double tempLong = start[0] - destination[0];
tempLat = tempLat*111;
tempLong = tempLong*85;
double Distance = Math.sqrt(Math.pow(tempLong, 2)+Math.pow(tempLat,2));
return Distance;
}
}
public BST(Node root, double[] start){
this.root = root;
this.start = start;
}
它是一个Tree,带有一个子类Node。
我的问题是,在Main类中,我无法正确初始化BST对象。
我这样做:
BST mcdonaldsLocations;
Node rootM = new Node(rootCoords, rootAddress);
mcdonaldsLocations = new BST(rootM, start);
它不起作用。所以我做了一些修补,得到了这个
BST mcdonaldsLocations = null;
Node rootM = mcdonaldsLocations.new Node(rootMCoords, rootMAddress);
mcdonaldsLocations = new BST(rootM, start);
编译,但有一个空指针错误。
答案 0 :(得分:2)
我不会将Node
实现为内部类,而是来自演示目的:
您可以使用静态工厂 - 从代码中删除构造函数,然后执行:
public static BST generateBST(double[] start, String rootAddress) {
BST bst = new BST();
bst.start = start;
Node root = bst.new Node(start, rootAddress);
bst.root = root;
return bst;
}