【问题标题】:How can I implement Random in java如何在java中实现随机
【发布时间】:2015-06-22 03:07:19
【问题描述】:

好吧,我需要实现两个类StudentSchool。每个学生都有一个由number of arrivaldormitory number 组成的Id 数字,第二个应该是元素数组中的随机数。

然后我需要将这些学生注册到合适的学校,一共有四个。这个注册也必须是随机的。所以我在这里有学生和学校课程,

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 类中有 register 方法,可以将新学生注册到特定学校。

所以我的问题是我如何从学校班级获取数据size 以在学生班级中使用它???

我只是一个学生请不要评判我^^)

【问题讨论】:

  • 将大小变量设为静态并以静态方式获取。
  • 这和随机有什么关系?
  • 我承认这种联系对我来说似乎很随机。

标签: java


【解决方案1】:

当您将学生添加到学校时,您还应该告诉学生他们所在的学校。

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,学生就可以找到他们学校的规模。

【讨论】:

  • 非常感谢,这对我有帮助
【解决方案2】:

如果我正确理解您的问题,您需要在学生的setId() 方法中添加一个int 参数:

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

然后在 register() 方法上你会这样做:

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

希望对你有帮助,祝你好运!

【讨论】:

    猜你喜欢
    • 2015-01-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 2011-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-29
    相关资源
    最近更新 更多