jeudi 9 septembre 2021

How do I generate objects randomly in java?

I have an abstract class called "Student" and 2 subclasses "Graduate" and "Undergraduate", they both have the same parameters.

I want to create 10 Student objects randomly, some from the "Graduate" and some from the "Undergraduate" classes.

I want to print the displayStudent() method for all objects created, I got stuck on how to randomly generate the 10 students so they are all random of type graduates and undergraduates.

public abstract class Student {
    private int ID;
    private double GPA;
    
    public Student(int ID, double GPA) {
        this.ID = ID;
        this.GPA = GPA;
    }
    
    public int getID() {
        return ID;
    }

    public double getGPA() {
        return GPA;
    }
    
    public abstract String getLevel();

    
    public abstract String getStatus();
    
    public final String displayStudent() {
        return getLevel() + " ID>> " + getID() + ", GPA>> " + getGPA() + ", Status>> " + getStatus();
    }

} 


    public class Graduate extends Student{
    
    public Graduate(int ID, double GPA) {
        super(ID, GPA);
    }
    @Override
    public String getLevel() {
        return "graduate";
    }

    @Override
    public String getStatus() {
        if( getGPA() >= 3) {
            return "honor";
        } else if (getGPA() >= 2 && getGPA() <= 3) {
            return "good";
        } else {
            return "probation";
        }
    }
}
 

public class Undergraduate extends Student {
    public Undergraduate(int ID, double GPA) {
        super(ID, GPA);
    }

    @Override
    public String getLevel() {
        return "undergraduate";
    }
    
    @Override
    public String getStatus() {
        if( getGPA() >= 3) {
            return "honor";
        } else if (getGPA() >= 2 && getGPA() <= 3) {
            return "good";
        } else if( getGPA() > 0 && getGPA() < 2) {
            return "probation";
        } else {
            //for any number that is not in the range of the GPA
            return "invalid GPA!";
        }
    }
    
}
 



Aucun commentaire:

Enregistrer un commentaire