【发布时间】: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