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

枚举用法报错,说是空指针,不知道为什么
Java code


enum Number { A,two,three,four,five,six,seven,eight,nine,ten,J,Q,K,}
enum Color { diamonds,hearts,spade,plum,}

class Cards{
    public Number number;
    public Color color;
    public Cards(Number number,Color color){
        this.number = number;
        this.color = color;
    }
}

public class Pocker {
    private Cards []card;
    private int deck;
    public void init(int n){
        if(n<1)
            deck=1;
        else
            deck = n;
        card = new Cards[n*52];
        for(int i=0;i<52*n;++i){
            switch(i%13){
            case 1:card[i].number = Number.A;break;
            case 2:card[i].number = Number.two;break;
            case 3:card[i].number = Number.three;break;
            case 4:card[i].number = Number.four;break;
            case 5:card[i].number = Number.five;break;
            case 6:card[i].number = Number.six;break;
            case 7:    card[i].number = Number.seven;break;
            case 8:card[i].number = Number.eight;break;
            case 9:card[i].number = Number.nine;break;
            case 10:card[i].number = Number.ten;break;
            case 11:card[i].number = Number.J;break;
            case 12:card[i].number = Number.Q;break;
            case 13:card[i].number = Number.K;break;        
            }
            switch(i/13){
            case 0:card[i].color = Color.hearts;break;
            case 1:card[i].color=Color.diamonds;break;
            case 2:card[i].color = Color.plum;break;
            case 3:card[i].color=Color.spade;break;
            default:break;
            }
        }
    }
    
    public void printInfo(){
        for(int i=0;i<card.length;++i){
            if(i%13==0)
                System.out.println();
            System.out.println(card[i].color+" "+card[i].number);
        }
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        Pocker p = new Pocker();
        p.init(2);
        p.printInfo();
    }

}


错误在switch里面

------解决方案--------------------
跟枚举么有关系。是你的:card = new Cards[n*52];后面要进行card[i] = new Cards(……)。对象数组要记得给每个数组元素进行初始化。
------解决方案--------------------
数组对象使用前要初始化。。。
------解决方案--------------------
报错原因是card[i]为空
private Cards []card;//声明数组
card = new Cards[n*52];//给card数组分配内存空间
一个数组定以后,必须经过初始化才可以引用。。。。。你缺少初始化数组这一步

但是card[i].number的时候你已经在对数组进行操作了,所以card[0] = null