根据用户输入创建学生数组

时间:2017-03-11 13:58:16

标签: java arraylist

我正在尝试根据用户输入创建一系列数学学生,理科学生和计算机专业学生。

所以基本上用户应该选择他们想要添加的学生,然后输入学生的详细信息。

下面我添加了我到目前为止的代码:

主Java类:

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);
    }

}

学生班:

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课程:

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); 
    }
}

我将如何解决这个问题?

4 个答案:

答案 0 :(得分:0)

您可以询问每个输入上具有类型的学生数量并动态创建对象。 这是一个例子

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();
}

同样,你可以为别人写作。

答案 1 :(得分:0)

允许用户输入他的选择作为输入 你可以这样做(由你的评论解释)

伪代码 -

打印:

  • 为数学学生输入1

  • 为理科学生输入2

  • 为Comp学生输入3

输入选择

现在在您的代码中使用多个if else或更好的switch语句

 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
 }

答案 2 :(得分:0)

您可以使用ArrayList和switch case来让您的生活更轻松。你的代码应该是这样的:

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);
        }

    }

}

上面的代码要求提供课程名称(计算机,数学,科学),如果是其中之一,则会读取有关学生的所有信息以及相应课程的成绩。它创建对象并将其添加到列表students中。当添加所有信息时,它询问用户他/她是否想要添加另一个学生,如果他写了字母y,则再次进行所有这些,直到用户回答与字母y不同的内容(大多数字母n)例)。在这之后它打印所有的学生&#39;信息通过itterating列表。

注意:我认为在您的ComputerStudent类的代码中,您想要命名变量fortranGrade而不是fortanGrade(在getSubjects函数中也更改它)。

链接:

我希望这有助于你。如果您有任何问题或想要更多的东西,您可以这样做。

<强>更新

下面的代码执行相同的操作,但它使用for循环而不是switch case,正如您在评论中提到的那样。

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);
        }

    }

}

您还需要在类中添加函数,如下所述:

学生班:

public String getLessonName(){
    return "";
}

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

MathStudent课程:

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

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

ComputerStudent类:

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

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

ScienceStudent课程:

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

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

更改:代码首先使用学生类(studdentClasses)创建一个arraylist,并添加当前在项目中的学生的所有课程(MathStudentComputerStudentScienceStudent)。然后用户添加课程的名称。然后(而不是切换案例)有一个for循环,它通过studdentClasses列表进行检查,并检查用户所写的课程名称是否与学生的课程相同使用getLessonName函数。之后,询问学生的所有信息和科目的成绩,以及问题(给学生的物理等级),它使用函数getSubjectsNames。所有其他事情都像以前一样。

答案 3 :(得分:-2)

你有一个主类,这本质上是你需要的,但你需要从命令行读取。太棒了,从命令行运行。一旦你跑了,注意你做了什么,你也可以在那里传递参数。一旦你传递了参数,它们就会排成一行。此行在逻辑上是可拆分的,因此将其拆分为您的代码。例如,通过一些关键词之后的一对数字,比如科学和直到下一个关键词并再次从java中提出并在你那里问一个新问题。