我正在创建一个程序,它读取文本文件并将其中的信息设置为三叉树中的节点。我已经创建了 addNode 方法,但现在我正在研究读取导入的纺织品并提取正确信息、将其设置到节点并构建树的方法。一个文本文件以下列格式给出,用于创建自动帮助服务系统。
每个节点都有三个 String 类型的变量:label、prompt 和 message
root //label
Root Node //prompt
What Model is the Washing Machine? //message
root 3 //root signifies the next node to branch, and 3 is the # children
1 //label
WM200 //prompt
What is the problem? //message
2 //etc.
WM300
What is the problem?
3
WM400
What is the problem?
1 3
1-1
No Water.
Is the hose attached?
1-2
Water too hot.
Turn the temperature knob to warm.
1-3
Water too cold.
Turn the temperature knob to warm.
1-1 3
1-1-1
Yes, but the hose is broken.
Purchase a new hose.
1-1-2
No, didn't know there was a hose.
Plug it in the back.
1-1-3
Yes, but still no water.
Make sure the water valve is turned on.
每次有完整的信息量(标签、提示、消息)时,我需要将节点添加到树的正确位置(在父节点下,左对齐)
这是我为该方法提供的代码。(假设 addNode 方法正常工作并且从左到右添加节点)
addNode 方法有 4 个参数(标签、提示、消息、父标签)
parentLabel 是放置孩子的地方。Ex/root 是上面示例代码第 4 行中的父标签。
while(line != null) { //while there is still content in the file
String label = line; //set label to first line
line = reader.readLine();
String prompt = line; //set prompt to second line
line = reader.readLine();
String message = line; //set message to third line
line = reader.readLine();
String parentLabel = "";;
String numChildren = "";
if(line.contains(" ")) {
parentLabel = line.substring(0, line.indexOf(" ")); //parent label up to first space
numChildren = line.substring(line.indexOf(" "), line.indexOf("\n")); //number of children from space to end
} else
numChildren = line; //if no space, line is number of children
tree.addNode(label, prompt, message, null); //add that node (parentLabel would be null becuase first node)
for(int i = 0; i < Integer.parseInt(numChildren); i++) {
line = reader.readLine();
label = line; //set label to first line
line = reader.readLine();
prompt = line; //set prompt to second line
line = reader.readLine();
message = line; //set message to third line
tree.addNode(label, prompt, message, parentLabel); //add node
}
我认为我的代码很接近,但它并不总是适用于给定的模式。文本文件将始终采用该格式,但是标签不必采用任何特定格式,并且它们不一定由数字和破折号组成。
对此的任何帮助将不胜感激。谢谢