日期:2014-05-20  浏览次数:20952 次

空指针异常,? - -#
Java code


import java.awt.*;
import javax.swing.*;

class Astar extends JPanel {
    int[][] map = {
                    {1,1,0,0,0,0,0,0,0,0},
                    {1,0,0,0,0,0,0,0,0,0},
                    {0,0,0,0,0,0,0,0,0,0},
                    {0,0,0,1,1,1,1,1,0,0},
                    {0,0,0,0,0,0,0,1,0,0},
                    {0,0,0,0,0,0,0,1,0,0},
                    {0,0,0,0,0,0,0,1,0,0},
                    {1,1,1,0,0,0,0,0,0,0},
                    {1,0,0,0,0,0,0,0,0,0},
                    {0,0,0,0,0,0,1,1,0,0},
               };
     Cell[][] map1;
     
     public Astar(){
         map1 = new Cell[10][10];
        for(int i=0;i<10;i++)
            for(int j=0;j<10;j++)
                map1[i][j].value = map[i][j];
         JFrame f = new JFrame();
         f.setBounds(100,100,600,500);
         f.add(this);
         f.setVisible(true);
     } 
    public void paintComponent(Graphics g){
        for(int i=0;i<10;i++){
            for(int j=0;j<10;j++){
                if(map[i][j]==0){
                    g.draw3DRect(40*j,40*i,40,40,true);
                    g.drawString(map1[i][j].toString1(),40*j,40*i);
                }
                else if(map[i][j]==1)
                    g.fill3DRect(40*j,40*i,40,40,true);    
                }
            }
    }
    public static void main(String args[]){
        new Astar();    
    }
    class Cell{
        int value;
        boolean seen;
        boolean open;
        int direction;
        Cell(){
            seen = true;
            open = true;    
        }
        public String toString1(){
            if(open)
                return "Open";
            else return "Closed";    
        }    
    }
}




------解决方案--------------------
for(int i=0;i<10;i++)
for(int j=0;j<10;j++)
{
map1[i][j]= new Cell();
map1[i][j].value = map[i][j];
}
------解决方案--------------------
虽然map1 = new Cell[10][10];你初始化了一个二维Cell数组,但是你并没有对里面的每个Cell进行初始化,所以默认初始化值为null,用null来调用value,所以就报错了
------解决方案--------------------
空指针就是 xx.xx .前面的那个值为null; 比较好找
------解决方案--------------------
正解!
探讨
虽然map1 = new Cell[10][10];你初始化了一个二维Cell数组,但是你并没有对里面的每个Cell进行初始化,所以默认初始化值为null,用null来调用value,所以就报错了

------解决方案--------------------
数组默认是每个值都是null