我不明白为什么我得到一个arrayindexoutofbounds异常。
这是我的代码如下。我认为导致问题的位在addnode方法
中import java.io.*;
import static java.lang.System.out;
import java.util.*;
class Tree
{
Node root;
class Node
{
int data;
int id;
Node parent;
List<Node> children;
public Node(int d, int i, List<Node> k)
{
this.data = d;
this.id = i;
this.children = k;
}
}
Node addNode(int[][] treetxt, Tree tree, int n)
{
System.out.println(n);
List<Node> k = new ArrayList<Node>();
if(treetxt[2][n-1] != 0)
{
for(int i=2; i!=0; i++)
{
k.add(addNode(treetxt, tree, treetxt[i][n]));
}
}
return new Node(n,treetxt[1][n],k);
}
}
class DSAP3
{
int n;
List<Tree.Node> all = new ArrayList<Tree.Node>();
Tree club = new Tree();
int[][] treedata;
public static void main(String [ ] args)
{
DSAP3 tourney = new DSAP3();
String line;
File file = new File("P3eg1.txt");
try
{
Scanner in = new Scanner(file);
tourney.n = in.nextInt();
tourney.treedata= new int[tourney.n][tourney.n];
line = in.nextLine();
for(int y=0; y<tourney.n; y++)
{
line = in.nextLine();
Scanner lineread = new Scanner (line);
int x = 2;
tourney.treedata[0][y]=lineread.nextInt();
tourney.treedata[1][y]=lineread.nextInt();
lineread.next();
while(lineread.hasNextInt())
{
tourney.treedata[x][y]=lineread.nextInt();
x++;
}
}
tourney.club.root = tourney.club.addNode(tourney.treedata, tourney.club, 1);
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file ");
System.exit(0);
}
}
}
例外是
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at Tree.addNode(DSAP3.java:28)
at Tree.addNode(DSAP3.java:32)
at DSAP3.main(DSAP3.java:77)
在抛出异常之前,add nodes方法中的print语句打印1然后是0
我该如何解决这个问题 提前致谢