[英]How to return random string from a non binary tree in java
I have a method to return a String from a non binary tree but its throwing "IllegalArguementException" What am I doing wrong. 我有一种从非二进制树返回字符串的方法,但是抛出“ IllegalArguementException”,这是我做错了什么。
public String getRandomWord(Node node, String word){
Random randomGenerator = new Random();
randomInt = 0;
current = node;
if(node.getChildren() == null){
//System.out.println(node.getData());
return word;
}
while(node.getChildren() != null){
randomInt = randomGenerator.nextInt(node.getChildren().size());
randomInt = randomGenerator.nextInt(2);
current = node.getChildren().get(randomInt);
word += current.getData();
//System.out.print(current.getData()+"\n");
getRandomWord(current, word);
}
return word;
}
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:604)
at java.util.ArrayList.get(ArrayList.java:382)
at treeapp.Tree.getRandomWord(Tree.java:71)
at treeapp.Tree.getRandomWord(Tree.java:74)
at treeapp.Tree.getRandomWord(Tree.java:74)
at treeapp.Tree.getRandomWord(Tree.java:74)
at treeapp.Tree.getRandomWord(Tree.java:74)
at treeapp.Tree.getRandomWord(Tree.java:74)
at treeapp.Tree.getRandomWord(Tree.java:74)
at treeapp.Main.main(Main.java:34)
Java Result: 1
I think you meant to delete this line, which will overwrite the previous random number and assumes that there are always 2 children. 我认为您打算删除此行,它将覆盖之前的随机数,并假定始终有2个子代。
randomInt = randomGenerator.nextInt(2);
Also, I'm not sure exactly what the method is supposed to do, but you may want to change the while
to an if
if I understand it correctly. 另外,我不知道到底是什么方法应该做的事,但你可能希望改变while
至if
,如果我理解正确。
Finally, change if(node.getChildren() == null)
to if(node.getChildren().size()==0)
. 最后,将if(node.getChildren() == null)
更改为if(node.getChildren().size()==0)
。 When the node has no children, getChildren()
returns an empty list, not null
. 当节点没有子节点时, getChildren()
返回一个空列表,而不是null
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.