2016-12-30 76 views
-2

我有練習,我寫了一個CourseManager5類,它存儲了給定的 類中的學生對象列表。每個學生都有一個ID,名字,分數。該類允許用戶添加 學生,並顯示學生的數據。這裏是UML圖: enter image description here 的方法是:對象數組-java-

  • CourseManager5:一個初始化的屬性,並創建一個構造函數排列100的學生。
  • getNStudents:返回當前學生人數。
  • addStudent:將具有給定對象的學生添加到列表中。如果課程已滿,則 將顯示錯誤消息:「錯誤:課程已滿」。
  • displayStudent:顯示索引爲i的學生的所有數據。 寫稱爲TestCourseManager5主類main方法,將 做到以下幾點:
    • 它創建了一個CourseManager5對象。
    • 然後,通過閱讀用戶的ID,姓名和分數,增加了3名學生。
    • 然後,它顯示在課堂上的所有學生。

我寫的程序..但我用的方法有問題displayStudent ..我不爲什麼!

還有一件事:是方法addStudent正確??

這是我的計劃:

import java.util.Scanner; 
public class TestCourseManager5 { 
    public static void main(String[] args) { 
     Scanner s = new Scanner(System.in); 
     courseManager5 cm = new courseManager5(); 
     int num =0; 
     for(int i =0; i < 3;i++){ 
      System.out.println("Please enter the ID, name, and score of student "+num+":"); 
      int id = s.nextInt(); 
      String name = s.next(); 
      double score = s.nextDouble(); 
      student su = new student(id, name, score); 
      cm.addStudent(su); 
      num++;} 

     System.out.println("Student are: "); 
     for(int i=0;i<cm.getNStudent();i++){ 
     cm.displayStudent(i); 
     }}} 

public class student { 
    private int id; 
    private String name; 
    private double score;     
    public student(int id, String name, double score){ 
     this.id = id; 
     this.name = name; 
     this.score = score;} 

    public int getId(){ 
     return id;} 

    public String getName(){ 
     return name;} 

    public double getScore(){ 
     return score;}} 

public class courseManager5 { 
private student []students; 
private int nStudent; 
public static int MAX_SIZE = 100; 

public courseManager5(){ 
    students = new student[MAX_SIZE]; 
    nStudent = 0;} 

/傳遞addStudent與thegiven對象添加到列表添加學生。如果課程已滿, 它打印錯誤信息:「ERROR:當然是完全」是我的方法正確/

public void addStudent (student newStudent){ 
    if(nStudent < MAX_SIZE) 
     nStudent++; 
    else 
     System.out.println("ERROR: COURSE IS FULL");} 

public int getNStudent(){ 
    return nStudent;} 

public void displayStudent(int i){// my problem here ! 
     System.out.println(students[i].getId()+", "+students[i].getName()+", "+students[i].getScore()); 
    } 
} 
+2

是的,有什麼問題? – ifly6

+0

我有方法displayStudent問題,我不知道爲什麼? – jeedo

+2

是什麼問題? – ifly6

回答

0

你的問題是在addStudent()。你從未將學生添加到數組中。所以,在displayStudent()中導致null。試試這個:

public void addStudent (student newStudent){ 
    if(nStudent < MAX_SIZE) 
     students[nStudent++] = newStudent; 
    else 
     System.out.println("ERROR: COURSE IS FULL");} 
+1

它的工作..非常感謝你 – jeedo

0

在你addStudent方法你不添加到陣列通過學生?試試這個:

students[nStudent] = newStudent; 
+0

謝謝你..它的工作..我有下週的考試..你知道任何頻道在youtube,幫助我的對象數組..因爲我知道一點呢? ...再次感謝你.. – jeedo

+0

如果它的工作,然後投票的答案,並接受它作爲答案。爲了更好地理解java數組,請看這裏[這裏](http://www.javawithus.com/tutorial/array-of-objects)和這個[here](http://docs.oracle.com)。com/javase/specs/jls/se7/html/jls-10.html)。 – Jayfray