我想構建一個對象數組,但試圖設置它們時得到一個空指針異常。試圖建立一個對象數組,但得到一個空指針異常
爲什麼當它到達第一輛車[i]時,它會拋出異常?
下面是代碼: 例1:http://pastebin.com/4h4W3770 例2:http://pastebin.com/4GL4FhrW
我想構建一個對象數組,但試圖設置它們時得到一個空指針異常。試圖建立一個對象數組,但得到一個空指針異常
爲什麼當它到達第一輛車[i]時,它會拋出異常?
下面是代碼: 例1:http://pastebin.com/4h4W3770 例2:http://pastebin.com/4GL4FhrW
當你創建一個數組對象時,它的所有元素都被初始化了t null
(如果數組包含java.lang.Object
的子類)。您需要在訪問任何屬性之前實例化每個元素。您正在嘗試設置Cars
屬性,而不在代碼實例它下面,這是造成NullPointerException
:
car[i].setPlate(info[0]);
在此之前,你需要初始化Car的實例是這樣的:
public static void main(String[] args) {
String sCurrentLine;
try (BufferedReader br = new BufferedReader(new FileReader("cars.txt"))) {
while ((sCurrentLine = br.readLine()) != null) {
String[] info = sCurrentLine.split(",");
for (int i = 0; i < 10; i++) {
car[i] = new Cars(); //instantiate Cars object or next statement will throw NPE
car[i].setPlate(info[0]);
car[i].setLocation(Integer.parseInt(info[1]));
car[i].setSpeed(Integer.parseInt(info[2]));
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
你有一個簡單的問題。你從未初始化過car[i]
。 car[i]
是null
當您嘗試對null
變量進行任何操作時,您將得到一個NullPointerException
。
所以解決的辦法就是初始化car[i]
如下圖所示:
for (int i = 0; i < 10; i++) {
car[i] = new Cars(); //intialise the car.
car[i].setPlate(info[0]);
car[i].setLocation(Integer.parseInt(info[1]));
car[i].setSpeed(Integer.parseInt(info[2]));
}
這個我想會解決你的問題。
謝謝!這是正確的答案。 – anaruson
在這種情況下,您可以將此答案標記爲已接受並答覆此問題:) –