【发布时间】:2016-09-15 02:45:20
【问题描述】:
我有一个 txt 文件(表示图中的节点和成本),格式如下:
A B 2
A C 3
A D 4
BC 2 . . .
我有一个名为Node 的类来表示上述数据。以下是我的Node 课程
class Node{
Node leftchild;
Node rightchild;
int cost;
public Node(Node firstchild, Node secondchild, int cost){
this.leftchild = firstchild;
this.rightchild = secondchild;
this.cost = cost;
}
public Node(Node firstchild, Node secondchild) {
this.leftchild = firstchild;
this.rightchild = secondchild;
}
public ArrayList<Node> getChildren(){
ArrayList<Node> childNodes = new ArrayList<Node>();
if(this.leftchild != null)
{
childNodes.add(leftchild);
}
if(this.rightchild != null)
{
childNodes.add(rightchild);
}
return childNodes;
}
public boolean removeChild(Node n){
return false;
}
}
我现在想从文件中读取数据(上述格式)并将其存储在一个三维数组中,如下所示
[A] [B] [2]
[A] [C] [3]
..等等
我有以下方法从文件中读取数据并将其存储在数组中,但是在将令牌添加到数组列表时出现错误。
我的错误是:Incompatible types: String cannot be converted to Node.
我不确定如何解决这个问题。非常感谢任何形式的帮助。谢谢。
public Node[][][] getNodes(File file) throws IOException {
FileReader inputHeuristic = new FileReader(file);
BufferedReader bufferReader = new BufferedReader(inputHeuristic);
String line;
List list = new ArrayList();
while ((line = bufferReader.readLine()) != null) {
String[] tokens = line.split(" ");
list.add(new Node(tokens[0], tokens[1], tokens[2]));
}
bufferReader.close();
return list.toArray(new Node[list.size()]); // converting list to array
}
【问题讨论】:
-
当对应的构造函数期望两个
Node和一个int值:public Node(Node firstchild, Node secondchild, int cost)时,为什么你认为你应该能够做到new Node(tokens[0], tokens[1], tokens[2])? -
我不知道如何添加这些类型,我用谷歌搜索并找到了它
-
我不确定如何将
Node类类型添加到数组列表中。我知道标记只适用于整数,但如何添加类类型?我不知道。我对此有点陌生。 -
然后阅读教程。谷歌搜索你不理解的代码是学习编程的一种非常糟糕的方式,尽管这似乎是当今最流行的方式。
标签: java arrays search arraylist