2015-05-18 62 views

回答

2

當你創建一個數組對象時,它的所有元素都被初始化了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(); 
     } 

    } 
+0

謝謝!這是正確的答案。 – anaruson

+0

在這種情況下,您可以將此答案標記爲已接受並答覆此問題:) –

0

你的setter方法沒有得到任何輸入/參數,所以他們不知道他們應該設置什麼:

public void setSpeed() { 
    this.speed = speed; 
} 

變化到:

public void setSpeed(Integer speed) { 
    this.speed = speed; 
    } 
+0

對不起,我在問題中使用了一箇舊鏈接,我更新了它並且已經修復了這個問題。任何想法仍然? – anaruson

+0

啊,你的例子現在更有意義了。認爲sud29現在有正確的答案。 – hamena314

0

你有一個簡單的問題。你從未初始化過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])); 
} 

這個我想會解決你的問題。

相關問題