大家看下!
1. import java.awt.*;
2. import javax.swing.*;
3. class HTNode
4. {
5. int weight;
6. int parent;
7. int lchild;
8. int rchild;
9. }
10. public class HuffmanTree extends JApplet
11. {
12. public int s1,s2;
13. int n=(int)(2+9*Math.random());//随机生成结点的个数
14. int m=2*n-1;
15. public void paint(Graphics g)
16. {
17. Graphics2D g2=(Graphics2D)g;
18. HTNode[] HT=new HTNode[m+1];
19. int i;
20. int w[]=new int[n];//存取每个结点的权值
21. for(i=0;i <n;i++)
22. w[i]=(int)(1+20*Math.random());
23. for(i=1;i <=n;i++)
24. {
25. HT[i].weight=w[i-1];
26. HT[i].parent=0;
27. HT[i].lchild=0;
28. HT[i].rchild=0;
29. }
30. for(i=n+1;i <=m;i++)
31. {
32. HT[i].weight=0;
33. HT[i].parent=0;
34. HT[i].lchild=0;
35. HT[i].rchild=0;
36. }
37. for(i=n+1;i <=m;i++)
38. {
39. Select(HT,i-1);
40. HT[s1].parent=i;
41. HT[s2].parent=i;
42. HT[i].lchild=s1;
43. HT[i].rchild=s2;
44. HT[i].weight=HT[s1].weight+ HT[s2].weight;
45. }
46. for(i=1;i <=n;i++)
47. g2.drawString(Integer.toString(HT[i].weight),20*i,100);
48. g2.dispose();
49. }
50. public void Select(HTNode HT[],int n)
51. {
52. int i,j;
53. for(i=1;i <= n;i++) if(HT[i].parent==0){s1=i;break;}
54. for(j=i+1;j <=n;j++)
55. if(HT[j].parent==0){s2=j;break;}
56. for(i=1;i <=n;i++)
57. if((HT[s1].weight> HT[i].weight)&&(HT[i].parent==0)&&(s2!=i)) s1=i;
58. for(j=1;j <= n;j++)
59. if((HT[s2].weight> HT[j].weight)&&(HT[j].parent==0)&&(s1!=j)) s2=j;
60. }
61. }
为什么上面程序报下面的错:
Exception in thread "AWT-EventQueue-1 "
java.lang.NullPointerException at HuffmanTree.paint(HuffmanTree.java:25)
------解决方案--------------------HTNode[] HT=new HTNode[m+1];
你这样初始化数组之后还要对数组的每一个元素进行初始化