gpt4 book ai didi

java - 它如何返回 NullPointerException?

转载 作者:行者123 更新时间:2023-12-01 22:17:26 25 4
gpt4 key购买 nike

public class TestDogs {

public static void main(String [] args) {

Dog [][] theDogs = new Dog[3][];
System.out.println(theDogs[2][0].toString());
}
}

class Dog{ }

最佳答案

theDogs[2] 数组为空,因为您没有初始化它。即使您初始化了它,theDogs[2][0] 仍将为 null,因此对其调用 toString 仍会抛出 NullPointerException

如何初始化数组和 Dog 实例的示例:

Dog [][] theDogs = new Dog[3][];
theDogs[2] = new Dog[7]; // initialize the 3rd row of theDogs 2D array
theDogs[2][0] = new Dog (); // initialize the Dog instance at the 1st column of the 3rd row
System.out.println(theDogs[2][0].toString()); // now you can execute methods of theDogs[2][0]

关于java - 它如何返回 NullPointerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30724408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com