輸入構建樹在Java中,我試圖建立使用從文件數據的任意大小的樹。在文件中,每個節點都是它自己的行,並且分支由特定關鍵字分隔。目前,我正在將文件讀入列表中,逐項閱讀,並查找關鍵字以構建分支。在開始第一個分支之後,我很難理解如何繼續前進。以下是我的樹類和測試輸入文件。我意識到測試輸入可能被認爲對測試來說太大了,但實際測試輸入會有很多很多模型。最終目標是讓樹木代表哈雷戴維森自行車系列,併爲每輛自行車完全構建後的所有可用選項。例如,一個分支的一個部分看起來像:使用從文本文件
Harley(root) -> Model Line -> Model 1 -> color -> c1
如此反覆每個分支中的其他關鍵字。我的問題是如果我在populate()
的正確方向。我能想到的唯一方法就是有一個大的if...else if...
結構來連續檢查每個關鍵字,每個if...else
都有一個循環來填充關鍵字節點的子節點。即使我這樣做,我也不知道如何跳起來去做下一個分支,而且我知道這是製作樹的非常低效的方法。有什麼建議?謝謝。
Tree.java
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Tree
{
private Node root;
public Tree(String rootData)
{
root = new Node();
root.data = rootData;
root.children = new ArrayList<Node>();
}
public static class Node
{
private String data;
private Node parent;
private List<Node> children;
public Node(){}
public Node(String newNodeData, Node newNodeParent)
{
data = newNodeData;
parent = newNodeParent;
}
}
public void populate() throws IOException
{
//keep track of nodes for jumping up branches quickly
Node curNode = this.root;
Node curModelLine;
Node curModel;
//get the data
List<String> fileData = getData();
int nextDataLine = 0;
while (!fileData.isEmpty())
{
String curLine = fileData.get(nextDataLine);
if (curLine == "model line")
{
curModelLine = new Node(fileData.get(nextDataLine+1), this.root);
this.root.children.add(curModelLine);
}
/*Not sure where to go from here*/
nextDataLine++;
}
}
public static List<String> getData() throws IOException
{
List<String> filedata = new ArrayList<String>();
try
{
FileInputStream in = new FileInputStream("data.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
while((line = br.readLine())!= null)
{
filedata.add(line);
}
br.close();
}catch(Exception e)
{
System.out.println(e);
}
return filedata;
}
}
的data.txt:
harley
model line
linename1
modelname1
color
c1
c2
engine size
es1
es2
windsheild
w1
w2
lights
l1
l2
tire size
t1
t2
radio
r1
r2
abs
a1
a2
alarm
a1
a2
seat
s1
s2
bags
b1
b2
modelname2
color
c1
c2
engine size
es1
es2
windsheild
w1
w2
lights
l1
l2
tire size
t1
t2
radio
r1
r2
abs
a1
a2
alarm
a1
a2
seat
s1
s2
bags
b1
b2
linename2
modelname1
color
c1
c2
engine size
es1
es2
windsheild
w1
w2
lights
l1
l2
tire size
t1
t2
radio
r1
r2
abs
a1
a2
alarm
a1
a2
seat
s1
s2
bags
b1
b2
modelname2
color
c1
c2
engine size
es1
es2
windsheild
w1
w2
lights
l1
l2
tire size
t1
t2
radio
r1
r2
abs
a1
a2
alarm
a1
a2
seat
s1
s2
bags
b1
b2
這很有道理。所以在你的方法中,你可以在每個分支的末尾添加分隔符並使用它跳轉到根目錄。這是否適用於有許多子孫的節點?據我所知,它只會做沒有支行的分行。 – zakparks31191 2013-04-07 17:54:08
允許我編輯我的代碼。 – christopher 2013-04-07 17:55:32