2015-06-22 19 views
0

那麼,我需要實現兩個類StudentSchool。每個學生的Id號碼由number of arrivaldormitory number組成,第二個應該是元素數組中的隨機數。如何在java中實現Random

然後我需要將這些學生註冊到合適的學校,其中有四個。此註冊也必須是隨機的。所以我有學生在這裏的學校課程,

public class Student { 
private String name; 
private int id, size; 
private int dorm; 

/** 
* Constructor of a class Student 
* 
* @param n sets the name of the student 
*/ 
public Student(String n) { 
    name = n; 
    int d[] = {11, 19, 20, 22, 23, 24, 38, 39}; 
    Random r = new Random(); 
    dorm = d[r.nextInt(d.length)]; 
} 

/** 
* @return the name 
*/ 
public String getName() { 
    return name; 
} 

/** 
* @param name the name to set 
*/ 
public void setName(String name) { 
    this.name = name; 
} 


/** 
* @return the dorm 
*/ 
public int getDorm() { 
    return dorm; 
} 
/** 
* the id to set 
*/ 
public void setId() { 
    id = size; 
    id = id*100 + dorm; 
} 


/** 
* @return the id 
*/ 
public int getId() { 
    return id; 
} 


@Override 
public String toString() { 

    String result = "The student " + name + " has an id " + id + ". Located in the dormitory #" + dorm + "."; 
    return result; 

} 

在這裏,學校類,

import adt.Queue; 

public class School { 

private int size; 
private String name; 
private Queue q = new LinkedListQueue(); 

public School(String n) { 
    name = n; 
    size = 0; 
} 

public void register(Student st) { 

    q.enqueue(st); 
    size++; 

} 

public int getSize() { 
    return size; 
} 

public void viewStudents() { 
    System.out.println(q.toString()); 
} 

@Override 
public String toString() { 
    String str = "The School of " + name + ". The number of students is " + size + "."; 
    return str; 
} 

因此,大家可以看到,我已經註冊的學校類方法,註冊新的學生到一個特定的學校。

所以我的問題是,我如何才能從School類中獲取數據size以便在Student類中使用它?

我只是一個學生當您的學生加入到學校不要評判我請^^)

+0

使大小變量爲靜態並以靜態方式獲取。 –

+0

這與隨機有什麼關係? –

+2

我承認這個連接對我來說似乎很隨意。 – markspace

回答

0

,你也應該告訴學生他們是哪所學校。

添加現場並Student

public class Student { 
    private String name; 
    private int id, size; 
    private int dorm; 
    private School school; 

    public void setSchool(School school) { 
     this.school = school; 
    } 

的方法然後在School添加代碼,告訴學生。

public void register(Student st) { 
    q.enqueue(st); 
    size++; 
    st.setSchool(this); 
} 

現在只要school是學生不null,一個學生都能找到自己的辦學規模。

+0

非常感謝,幫助了我 –

0

如果我正確理解你的問題,你需要的是一個int參數添加到您的學生的setId()方法:

public void setId(int id) { 
    this.id = id * 100 + dorm; 
} 

,然後在register()方法,你會怎麼做:

public void register(Student st) { 
    q.enqueue(st); 
    st.setId(size++); 
} 

我希望能幫助你,祝你好運!