【问题标题】:Java Arraylist adding functionalityJava Arraylist 添加功能
【发布时间】: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


【解决方案1】:

您尝试做的事情没有多大意义。您不能将 String 类型的内容更改为类对象。要么您需要更改传递给构造函数的内容,要么您需要将实例变量的类型更改为 String。

我个人会将节点类型变量更改为字符串类型。您还需要解析令牌[2],使其成为一个 int。即 Integer.parseInt(token[2]);

【讨论】:

    猜你喜欢
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-27
    • 2014-04-24
    • 1970-01-01
    • 2013-11-29
    • 1970-01-01
    相关资源
    最近更新 更多