【问题标题】:Create Java Tree from text input从文本输入创建 Java 树
【发布时间】:2015-09-08 21:53:42
【问题描述】:

我需要生成表格数据源的树形表示,但我很难开始。数据是产品层次结构的表示

此输入的树结构如下所示:

到目前为止,我已经用 Java 编写了一个读取文本输入 (TSV) 并生成值的二维字符串数组的方法。从这里我不确定如何进行。数组类似乎没有定义关系或向树中添加节点所需的方法。

Java 代码:

public class ImportTSV  {   
// Global VARs
String[][] tsvArray;
List<String> lines; 

public static void main(String[] args) throws IOException{
    ImportTSV tsv = new ImportTSV();
    String [][] tmp = tsv.readTSV();
    tsv.arr2tree(tmp);
}

public String[][] readTSV() throws IOException{
    // Read File to lines object
    lines = Files.readAllLines(Paths.get("Input\\TestData_small.txt"), StandardCharsets.UTF_8);

    // Set Array bounds to # of lines in input source
    tsvArray = new String[lines.size()][];

    System.out.println("-- Full 2D Array --");
    // Build the array from TSV source
    for(int i=0; i<lines.size(); i++){
        tsvArray[i] = lines.get(i).split("\t");
        System.out.println(Arrays.deepToString(tsvArray[i]));
    }       
    return tsvArray;
}

public void arr2tree(String[][] arr){
    String[][] data = arr;
    String[] tmp = null;
    System.out.println(" ");
    System.out.println("-- Converting to Tree --");

    // Need a tree
    TreeMap<String, String> tm = new TreeMap<String, String>();

    // Loop through [][] to define each line
    for(int i=0;i<data.length;i++){
        // Then seperate by record
        for(int j=0;j<data[i].length-1;j++){
            // Set comparison variables
            String s1 = data[i][j];
            String s2 = data[i][j+1];

            // See the comparison
            System.out.println("Parent Check: " + s1);
            System.out.println("Child Check: " + s2);


            // Set the relationship in the tree if it doesnt exist
            if(tm.(s1)!=s2){
                tm.put(s1, s2); 
                System.out.println(tm.toString());
            }


        }           
    }       
}   

}

我对 Java 还很陌生,感谢任何帮助解决这个问题。

【问题讨论】:

  • 这看起来很像“为我做作业”的问题。我建议更多地考虑接下来的步骤并再次尝试。如果您在逻辑上遇到特定问题或使其正常工作,请再次发布。

标签: java arrays tree hashtable treemap


【解决方案1】:

首先,实现一个可以存储关系的Node 可能是明智的。

Here 是另一个问题的一个很好的例子。

public static class Node<T> {
    private T data;
    private Node<T> parent;
    private List<Node<T>> children;
}

在您的情况下,您可能可以将类型 T 更改为 String 并且由于您没有说父母是否有固定数量的孩子,List 也适合您。

【讨论】:

  • 谢谢,那么我想在遍历我的数组时定义一个节点,然后将其保存到地图中?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-15
  • 1970-01-01
  • 1970-01-01
  • 2013-02-27
相关资源
最近更新 更多