This question already has answers here:
What is a NullPointerException, and how do I fix it?
                            
                                (12个答案)
                            
                    
                2年前关闭。
        

    

我不知道我在这里搞砸了。看似在我的字符串数组上获取了空指针异常。

这是我在主Activity中调用的方法:

public void initializeLocalDealer() {
  String[] cars = new String[]{"Ford", "Chevy", "Chrysler", "Honda"};
    Dealer dealer = new Dealer();
    Dealer.setCars(cars);
}


这是我要填充的类对象。

public class Dealer {

    public String name;
    public Car[] car;

    public Dealer() { }

    public void setCars(String[] cars) {
        for(int i = 0; i < cars.length; i++) {
            car[i].name = cars[i];
        }
    }
}


我在这里错过了什么超级明显的事情?

最佳答案

Dealer dealer = new Dealer();
    dealer.setCars(cars);


Dealer.setCars(cars);修改为dealer.setCars(cars);

public class Dealer {

    public String name;
    public Car[] car;

    public Dealer() {

    }

    public void setCars(String[] cars) {
        -->car = new Car[cars.length];
        for(int i = 0; i < cars.length; i++) {
            car[i]= new Car(cars[i]);;

        }
    }


    }


在您的Car类中添加Constructor

public Car(String name) {
    name =this.name;
}

09-28 04:59