2017-04-04 110 views
-3

我想寫一些java代碼,但我得到一個異常。 我的問題是,我得到一個空指針異常,當我嘗試添加運動員 程序是接受運動員和計算平均得分這裏 是我的代碼arraylist不打印第一個元素

public class AthleteTest { 

     final int MAX_ATHELETE = 200; 
     private int count=0;  
     Athlete[] at = new Athlete[MAX_ATHELETE]; 
     Scanner sc = new Scanner(System.in); 

    public void addAthletes(){ 
      char add = 'Y'; 
      while(add == 'Y'){ 

       System.out.println("name:"); 
       String name = sc.nextLine(); 
       at[count].setName(name); 

       //Get athlete's Id number 
       System.out.println("id :"); 
       int id = sc.nextInt(); 
       at.setId(id); 

       //sc.nextLine(); 

       count++; 


       System.out.println("Would you like to add another athlete? Y/N"); 
       add = Character.toUpperCase(sc.next().charAt(0)); 
       sc.nextLine(); 
      } 
     } 
    } 


    my Athlete class is as follow 

    public class Athlete { 

     private String name; 
     private int id; 

     private double [] grades; 

     public Athlete(){ 
      this.name = null; 
      this.id= 0; 
     } 

     public Student(String name, int id){ 
      this.name = name; 
      this.id= id; 
     } 

     public String getName() { 
      return name; 
     } 

     public void setName(String name) { 
      this.name = name; 
     } 

     public int getId() { 
      return id; 
     } 

     public void setId(int id) { 
      this.id = id; 
     } 
    } 
+0

ArrayList在哪裏? –

+3

'at [count] .setName(name)' - 是在[count]'初始化?如果不是,那就是爲什麼你會得到'NullPointerException'。你應該在[count] = new Athlete()'首先執行 – 2017-04-04 17:40:44

+0

是的,我做過了,但它仍然給我一個空指針異常 –

回答

0

你得到,因爲你的例外在實例化它們之前,試圖訪問運動員對象。有了這個初始化:

Athlete[] at = new Athlete[MAX_ATHELETE]; 

你只是創建了一個地方舉行運動員實例。

改變你在循環代碼是這樣的:

System.out.println("name:"); 
String name = sc.nextLine(); 
at[count] = new Athlete(); // Add this line 
at[count].setName(name); 

而且你應該罰款。

+0

好的謝謝。我已經添加了該行,但是我仍然得到相同的空指針異常 –

+0

'NullPointerException'總是告訴你類和錯誤發生的位置。檢查這一行是什麼,你會知道什麼是錯的(或者至少需要初始化什麼變量) – 2017-04-04 18:43:51