如何从java中的非二叉树返回随机字符串

时间:2013-11-30 15:20:29

标签: java

我有一个方法从非二叉树返回一个字符串,但它抛出“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

1 个答案:

答案 0 :(得分:0)

我认为你打算删除这一行,它会覆盖以前的随机数,并假设总有2个孩子。

randomInt = randomGenerator.nextInt(2);

此外,我不确定该方法究竟应该做什么,但如果我理解正确,您可能希望将while更改为if

最后,将if(node.getChildren() == null)更改为if(node.getChildren().size()==0)。当节点没有子节点时,getChildren()会返回一个空列表,而不是null