【发布时间】:2015-12-04 23:46:29
【问题描述】:
给定字母表和每个字母的摩尔斯电码值...
a._
b_...
c_._.
d_.. //file to be read in
e.
f.._.
我正在尝试创建一棵树,通过扫描代码找到字母在树中的位置,然后向左分支以获得点,向右分支以获得破折号。
我用典型的numberNode left 和numberNode right 变量以及morseCode 和letter 创建了一个节点类。这是我的功能。
aList 是从文件中读取的已创建节点的数组列表。 rootNode 是树的根,没有设置 letter 或 morsecode。
public static void createTree(ArrayList<numberNode> aList, numberNode rootNode)
{
for (numberNode n : aList) //for each numberNode in aList
{
int lengthOfCode = n.getmorseCode().length()-1; //get the length of the morsecode
numberNode currentNode = rootNode; //sets currentNode to the rootNode at first
for (int i=0; i<lengthOfCode; i++)
{
char c = n.getmorseCode().charAt(i); //for each char in morsecode until it gets to the end
if (c == '.')
{
if (currentNode.getleft() = null) //if currentnode left is null
{
numberNode newLeftNode = new numberNode(); //create new node
currentNode.setleft(newLeftNode); //set current node left to the new node
if (i == lengthOfCode)
{
currentNode.setleft(n); //if end of morse code, set the current node left's to n
}
else
{
currentNode = newLeftNode; //else change current node to the newly created leftnode
}
}
else //if current node left is not null
{
if (i == lengthOfCode)
{
currentNode.setleft(n); //if at end of morse code
}
currentNode = currentNode.getleft(); //if not at end set current node to current node's left
}
}
if (c == '_')
{
if (currentNode.right() =null)
{
numberNode newRightNode = new numberNode();
currentNode.setleft(newRightNode);
if (i == lengthOfCode)
{
currentNode.setright(n);
}
else
{
currentNode = newRightNode;
}
}
else
{
if (i == lengthOfCode)
{
currentNode.setright(n);
}
currentNode = currentNode.getright();
}
}
}
}
}
我有几个问题...
我的算法至少是正确的吗?
是否有另一种方法可以做到这一点而不会那么难看?
如果您需要查看我的更多代码,请随时提出。感谢您的宝贵时间,我真的很感激!
编辑:当前正在运行,但是当我尝试使用...打印输出时...
for (numberNode n : nodeArray)
{
System.out.println(n.getletter());
System.out.println(n.getleft().getletter().toString()); //error here
System.out.println(n.getright().getletter());
System.out.println("");
}
我在指示的地方收到一个错误,关于出了什么问题有什么想法吗?
【问题讨论】:
-
您能更准确地了解错误吗?你能在你的代码中放一些 println 来跟踪它,并验证你的算法吗?
-
我得到一个 NPE,我至少在我的脑海里,验证了我的算法。在过去的几个小时里,我一直在运行它,似乎找不到任何问题。希望另一双眼睛能帮助我
标签: java object if-statement for-loop tree