我写了两个类,一个Tree和一个test,Tree用来创建一棵二叉树,随机产生的一棵二叉树,我用test来测试看能否建立树时就出现异常了
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class Tree
{
private Node arrayNode[];
private boolean flag[] = new boolean[26];
int Nodenum ;
int cursor ; 
public Tree()
{
cursor = 0;
Nodenum = (int)(Math.random()*20 + 6);
// System.out.println("" + Nodenum);
arrayNode = new Node[Nodenum];
arrayNode[0].data='s';
System.out.println("" + arrayNode[0].data); 
for(int j = 0;j<Nodenum;j++)
{
flag[j] = false;
System.out.println("constructor1 ");
arrayNode[j].data = 'w';
System.out.println("const");
arrayNode[j].color = Color.white;
}
}
public void Creat()
{
int counter = 0;
int k = (int)Math.random()*25 + 65;
int r = (int)Math.random()*100 + 154;
int g = (int)Math.random()*100 + 154;
int b = (int)Math.random()*100 + 154;
Color tempcolor = new Color(r,g,b);
char tempchar = (char)k;
arrayNode[cursor].data = (char)k;
arrayNode[cursor].color = tempcolor;
flag[k - 65] = true;
char a = 65;

counter++;
cursor ++;
while(counter<Nodenum)
{
k = (int)Math.random()*26 + 65;
r = (int)Math.random()*100 + 154;
g = (int)Math.random()*100 + 154;
b = (int)Math.random()*100 + 154;
if(k==91)
{
tempcolor = Color.white;
tempchar = ' ';
arrayNode[cursor].data = tempchar;
arrayNode[cursor].color = tempcolor;
counter++;
cursor++;
break;
}
else
{
tempcolor = new Color(r,g,b);
tempchar = (char)k;
}
if(arrayNode[(cursor-1)/2 - 1].data!=' ')
{
while(flag[k - 65]==true)
{
k = (int)Math.random()*26 + 65;
tempchar = (char)k;
}
arrayNode[cursor].data = tempchar;
arrayNode[cursor].color = tempcolor;
cursor++;
counter++;
}
}//end while
}//end creat
public void print()
{
for(int i=0;i<Nodenum;i++)
if(arrayNode[i].data!=' ')
System.out.println(arrayNode[i].data);
}
}
class Node
{
char data;
Color color;
}
//下面的类调用Tree类,编译没问题,一执行就出现NullPointerException异常
public class test
{
public static void main(String a[])
{
Tree atree = new Tree();
atree.Creat();
atree.print();
char c =(char) 67;
System.out.println(c);
}
}