0

I'm trying to create an array of math students, science students, and computer students based on the user input.

So basically the user should choose what student they want to add and then enter the student details.

Below I have added the code I have so far:

Main Java class:

public class Lab4 {
    public static final int DEBUG = 0;
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Student s[] = new Student[10];
        s[0] = new MathStudent(4,5);
        s[1] = new MathStudent(5,7);
        s[2] = new MathStudent(2,8);
        s[3] = new MathStudent(3,6);
        s[4] = new ScienceStudent(8,9);
        s[5] = new ScienceStudent(3,6);
        s[6] = new ScienceStudent(4,9);
        s[7] = new ComputerStudent(6,12);
        s[8] = new ComputerStudent(11,14);
        s[9] = new ComputerStudent(13,17);
    }

}

Student class:

public class Student {
    private String name;
    private int age;
    public String gender = "na";
    public static int instances = 0;

    // Getters
    public int getAge(){
        return this.age;
    }
    public  String getName(){
        return this.name;
    }

    // Setters
    public void setAge(int age){
        this.age = age;
    }
    public void setName(String name){
        if (Lab4.DEBUG > 3) System.out.println("In Student.setName. Name = "+ name);
        this.name = name;
    }

    /**
     * Default constructor. Populates name,age,gender,course and phone Number 
     * with defaults
     */
    public Student(){
        instances++;
        this.age = 18;
        this.name = "Not Set";
        this.gender = "Not Set";
    }

    /** 
     * Constructor with parameters 
     * @param age integer
     * @param name String with the name
    */
    public Student(int age, String name){
        this.age = age;
        this.name = name;
    }

    /** 
     * Gender constructor
     * @param gender 
     */
    public Student(String gender){
        this(); // Must be the first line!
        this.gender = gender;

    }

    /**
     * Destructor
     * @throws Throwable 
     */
    protected void finalize() throws Throwable{
        //do finalization here
        instances--;
        super.finalize(); //not necessary if extending Object.
    } 

    public String toString (){
        return "Name: " + this.name + " Age: " + this.age + " Gender: " 
               + this.gender;
    }

    public String getSubjects(){
      return this.getSubjects();
    }
}

MathStudent class:

public class MathStudent extends Student {
    private float algebraGrade;
    private float calculusGrade;

    public MathStudent(float algebraGrade, float calculusGrade) {
        this.algebraGrade = algebraGrade;
        this.calculusGrade = calculusGrade;
    }

    public MathStudent() {
        super();
        algebraGrade = 6;
        calculusGrade = 4;
    }

    // Getters
    public void setAlgebraGrade(float algebraGrade){
        this.algebraGrade = algebraGrade;
    }
    public void setCalculusGrade(float calculusGrade){
        this.calculusGrade = calculusGrade;
    }

    // Setters
    public float getAlgebraGrade() {
        return this.algebraGrade;
    }
    public float getCalculusGrade() {
        return this.calculusGrade;
    }

    /**
     * Display information about the subject
     * @return 
     */
    @Override
    public String getSubjects(){
        return("Algebra Grade: " + algebraGrade + " Calculus Grade: " 
                + calculusGrade);
    }
}

scienceStudent class:

public class ScienceStudent extends Student {
    private float physicsGrade;
    private float astronomyGrade;

    /**
     * Default constructor
     */
    public ScienceStudent() {
        super();
        physicsGrade = 6;
        astronomyGrade = 7;
    }

    public ScienceStudent(float physicsGrade, float astronomyGrade) {
        this.physicsGrade = physicsGrade;
        this.astronomyGrade = astronomyGrade;
    }

    // Getters
    public void setPhysicsGrade(float physicsGrade){
        this.physicsGrade = physicsGrade;
    }
    public void setAstronomyGrade(float astronomyGrade){
        this.astronomyGrade = astronomyGrade;
    }

    // Setters
    public float getPhysicsGrade() {
        return this.physicsGrade;
    }
    public float getAstronomyGrade() {
        return this.astronomyGrade;
    }

    /**
     * Display information about the subject
     * @return 
     */
     @Override
    public String getSubjects(){
        return("Physics Grade: " + physicsGrade + " Astronomy Grade: " 
                + astronomyGrade);
    } 
}

computerStudent class:

public class ComputerStudent extends Student {
    private float fortanGrade;
    private float adaGrade;

    /**
     * Default constructor
     */
    public ComputerStudent() {
        super();
        fortanGrade = 4;
        adaGrade = 9;
    }

    public ComputerStudent(float fortanGrade, float adaGrade) {
        this.fortanGrade = fortanGrade;
        this.adaGrade = adaGrade;
    }

    // Getters
    public void setFortanGrade(float fortanGrade){
        this.fortanGrade = fortanGrade;
    }
    public void setAdaGrade(float adaGrade){
        this.adaGrade = adaGrade;
    }

    // Setters
    public float getFortanGrade() {
        return this.fortanGrade;
    }
    public float getAdaGrade() {
        return this.adaGrade;
    }

    /**
     * Display information about the subject
     * @return 
     */
    @Override
    public String getSubjects(){
        return("Fortan Grade: " + fortanGrade + " Ada Grade: " + adaGrade); 
    }
}

How Would I go about this?

Jérôme
  • 1,133
  • 2
  • 16
  • 21
donk2017
  • 31
  • 1
  • 2
  • 7
  • Hi. Can you please post specific code where you have.problem? – minigeek Mar 11 '17 at 14:04
  • For user specific input you can use switch to create objects – minigeek Mar 11 '17 at 14:05
  • @minigeek Im trying to create an array of students based on user input in the main class. – donk2017 Mar 11 '17 at 14:05
  • Welcome to Stack Overflow! It looks like you may be asking for homework help. While we have no issues with that per se, please observe these [dos and don'ts](http://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions/338845#338845), and edit your question accordingly. (Even if this isn't homework, please consider the advice anyway.) – Joe C Mar 11 '17 at 14:06

4 Answers4

0

You can ask for the number of students with type on each input and dynamically create the object. Here is an example

System.out.println("Enter total number of students");
int n = scannerObject.nextInt();
Student students[] = new Students[n];
for(int i=0;i<n;i++){
  int type = scannerObject.nextInt();
  if(type == 1)
   students[i] = new MathStudent();
}

Similarly, you can write for others.

  • How would I ask for like what type student they want to add like MathStudent or Computer Student or Science Student and then add then once the user chooses the student then they will be asked for the grades for the student and then this will added to the array. – donk2017 Mar 11 '17 at 14:13
  • @donk2017 use switch statement – minigeek Mar 11 '17 at 14:23
0

For allowing user to enter his choice as input You can do this(interpreted by your comments)

Pseudo code -

Print:

  • Enter 1 for math student

  • Enter 2 for Science student

  • Enter 3 for Comp student

Input choice

Now in your code use either multiple if else or better switch statement

 switch(choice){
     case 1: create object of math student
             break;
     case 2: create object of science student
             break;
     case 3:create object of comp student
             break;
     default: if not above by default do this
 }
minigeek
  • 1,615
  • 1
  • 12
  • 24
0

You could use an ArrayList and switch case to make your life easier. Your code should be like this:

import java.util.ArrayList;
import java.util.Scanner;

public class Students {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        ArrayList<Student> students = new ArrayList<>();
        int age;
        boolean addMore = true;
        String name, gender;
        Student st;

        while (addMore) {

            System.out.print("Give lesson (Computers, Math, Science): ");
            String lesson = input.nextLine();

            switch (lesson) {
                case "Math":

                    // Read student's info

                    System.out.print("Give student's name: ");
                    name = input.nextLine();
                    System.out.print("Give student's gender: ");
                    gender = input.nextLine();
                    System.out.print("Give student's age: ");
                    age = input.nextInt();

                    System.out.print("Give student's Algebra grade: ");
                    int alg = input.nextInt();
                    System.out.print("Give student's Calculus grade: ");
                    int calc = input.nextInt();

                    input.nextLine(); // This is needed in order to make the next input.nextLine() call work (See here: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo )

                    // Create the student object and pass info

                    st = new MathStudent(alg, calc);
                    st.setName(name);
                    st.setAge(age);
                    st.gender = gender;

                    students.add(st); // Adding the student in the list

                    System.out.println(st);
                    System.out.println(((MathStudent) st).getSubjects());

                    break;

                case "Science":

                    // Read student's info

                    System.out.print("Give student's name: ");
                    name = input.nextLine();
                    System.out.print("Give student's gender: ");
                    gender = input.nextLine();
                    System.out.print("Give student's age: ");
                    age = input.nextInt();

                    System.out.print("Give student's Physics grade: ");
                    int physics = input.nextInt();
                    System.out.print("Give student's Astronomy grade: ");
                    int astronomy = input.nextInt();

                    input.nextLine();// This is needed in order to make the next input.nextLine() call work (See here: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo )

                    // Create the student object and pass info

                    st = new ScienceStudent(physics, astronomy);
                    st.setName(name);
                    st.setAge(age);
                    st.gender = gender;

                    students.add(st); // Adding the student in the list

                    System.out.println(st);
                    System.out.println(((ScienceStudent) st).getSubjects());

                    break;

                case "Computers":

                    // Read student's info

                    System.out.print("Give student's name: ");
                    name = input.nextLine();
                    System.out.print("Give student's gender: ");
                    gender = input.nextLine();
                    System.out.print("Give student's age: ");
                    age = input.nextInt();

                    System.out.print("Give student's Fortran grade: ");
                    int fortran = input.nextInt();
                    System.out.print("Give student's Ada grade: ");
                    int ada = input.nextInt();

                    input.nextLine();// This is needed in order to make the next input.nextLine() call work (See here: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo )

                    // Create the student object and pass info

                    st = new ComputerStudent(fortran, ada);
                    st.setName(name);
                    st.setAge(age);
                    st.gender = gender;

                    students.add(st); // Adding the student in the list

                    System.out.println(st);
                    System.out.println(((ComputerStudent) st).getSubjects());

                    break;

                default:
                    System.out.println("Wrong lesson");
                    addMore = false;
                    break;

            }

            if (addMore) {
                System.out.println("Add another student? (y/n)");
                String ans = input.nextLine();
                addMore = ans.equals("y");
            } else {
                addMore = true;
            }
        }

        System.out.println("Students");

        for (Student student : students) {
            System.out.println(student);
        }

    }

}

The code above asks for the lesson name (Computers, Math, Science) and if it is one of them it reads all the info about the student and the grades for the corresponding lesson. It creates the objects and adds them in the list students. When all info is added, it asks the user if he/she wants to add another student and if he writes the letter y, then all these are made again, until the user answers something different than the letter y (the letter n in most cases). After these it prints all the students' info by itterating the list.

Note: I think in your code for the ComputerStudent class, you meant to name the variable fortranGrade and not fortanGrade (change it also in the getSubjects function).

Links:

I hope this helped you. If you have any questions or wanted something more you can do it.

UPDATE

The code below does the same things, but it uses for loop instead of switch case, as you asked in your comment.

package students;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Lab4 {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        ArrayList<Student> students = new ArrayList<>();
        int age;
        boolean addMore = true;
        String name, gender;
        Student st;

        ArrayList<Class<?>> studentClasses = new ArrayList<>();

        studentClasses.add(MathStudent.class);
        studentClasses.add(ComputerStudent.class);
        studentClasses.add(ScienceStudent.class);

        while (addMore) {

            System.out.print("Give lesson (Computers, Math, Science): ");
            String lesson = input.nextLine();

            addMore = false;
            for (Class studentClass : studentClasses) {

                try {

                    st = (Student) studentClass.newInstance();

                    if (st.getLessonName().equals(lesson)) {

                        // Read student's info

                        System.out.print("Give student's name: ");
                        name = input.nextLine();
                        System.out.print("Give student's gender: ");
                        gender = input.nextLine();
                        System.out.print("Give student's age: ");
                        age = input.nextInt();

                        System.out.print("Give student's " + st.getSubjectsNames()[0] + " grade: ");
                        float firstSubj = input.nextFloat();
                        System.out.print("Give student's " + st.getSubjectsNames()[1] + " grade: ");
                        float secondSubj = input.nextFloat();

                        input.nextLine(); // This is needed in order to make the next input.nextLine() call work (See here: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo )

                        // Create the student object and pass info

                        st = (Student) studentClass.getConstructor(float.class, float.class).newInstance(firstSubj, secondSubj);
                        st.setName(name);
                        st.setAge(age);
                        st.gender = gender;
                        students.add(st); // Adding the student in the list                    

                        System.out.println(st);
                        System.out.println(st.getSubjects());

                        addMore = true;
                        break;
                    }

                } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
                    Logger.getLogger(Lab4.class.getName()).log(Level.SEVERE, null, ex);
                }

            }

            if (addMore) {
                System.out.println("Add another student? (y/n)");
                String ans = input.nextLine();
                addMore = ans.equals("y");
            } else {
                System.out.println("Wrong lesson. Try again.");
                addMore = true;
            }
        }

        System.out.println("Students");

        for (Student student : students) {
            System.out.println(student);
        }

    }

}

You also need to add the functions in the classes as mentioned bellow:

Student class:

public String getLessonName(){
    return "";
}

public String[] getSubjectsNames(){
    return new String[] {"", ""};
}

MathStudent class:

@Override
public String[] getSubjectsNames(){
    return new String[] {"Algebra", "Calculus"};
}

@Override
public String getLessonName(){
    return "Math";
}

ComputerStudent class:

@Override
public String[] getSubjectsNames(){
    return new String[] {"Fortran", "Ada"};
}

@Override
public String getLessonName(){
    return "Computers";
}

ScienceStudent class:

@Override
public String[] getSubjectsNames(){
    return new String[] {"Physics", "Astronomy"};
}

@Override
public String getLessonName(){
    return "Science";
}

Changes: The code firstly creates an arraylist with the student classes (studdentClasses) and adds all the classes for the students that are currently in the project (MathStudent, ComputerStudent, ScienceStudent). Then the user adds the lesson's name. Then (instead of the switch case) there is a for loop which itterates through the studdentClasses list and checks if the lesson's name that the user has written is the same with a student's class by using the getLessonName function. After that all the info for the student are asked and the grades for the subjects, and for the question (Give student's Physics grades) it uses the function getSubjectsNames. All the other things are like before.

Community
  • 1
  • 1
Thanasis1101
  • 1,456
  • 3
  • 10
  • 28
  • How can I implement it using a For loop instead of switch case? – donk2017 Mar 11 '17 at 15:28
  • What do you mean by using a for loop? Do you want to have a for loop for all types of lesson and in it to ask for the info? Give an example of how you imagine it. – Thanasis1101 Mar 11 '17 at 15:40
  • Like have a for loop and inside it, it should ask something like do you want to add a computer student, science student, math student, or exit and then should add those details to an array based on the user input and should repeat the question until the user enters exit. – donk2017 Mar 11 '17 at 16:26
  • Doesn't have to be For loop can be while loop aswell. – donk2017 Mar 11 '17 at 16:26
-2

You have a main class, that's what you need essentially, but you need to read from command line. Great, run from command line. Once you run, pay attention to what you did, you can pass parameters there as well. once you pass parameters, they go in line. This line is logically splitable, so split it within you code. for instance by pair of numbers after some key word like science and until next keyword and put again from java and ask a new question once you there.

Vitali Pom
  • 620
  • 1
  • 7
  • 28