小编典典

如何在一个对象中存储一个字符串和两个并行的arraylist。(java)

java

大家好,几天前我问过以下问题,但仍然有些麻烦。

“以下是原始帖子”,
我想存储一个学生姓名,并且每个姓名都有两个与该姓名相关联的ArrayList。我想把所有这些都放在一个类Student_quizes或类似的东西中

所以我基本上是想在一个对象中存储studentName,quizNames arraylist和quizScores
arraylist。quizNames和quizScores将是并行的。

我不确定我是否一整天都在尝试这种正确的方法,我很困惑,有人对我如何更好地做到这一点有任何建议吗?

很抱歉,如果我的问题令人困惑,我想程序会像这样运行。

输入学生姓名

迈克尔

输入测验

科学

输入测验分数

80

添加另一个测验是/否?

ÿ

输入测验…

添加其他学生是/否?

是的…

学生姓名:迈克尔

测验名称:科学,得分:80

测验名称:数学,分数:85

学生姓名:乔

测验名称:科学,得分60

目前,我的代码无处不在,但我张贴的内容不正确。

这是主要的


package Student_Quizes;

import java.util.ArrayList;
import java.util.Scanner;
import static student.student_main.print;

public class Student_quizes_main {

    public static void main(String[] args) {

        boolean addStudents = true;
        addStudent();

    }

    public static void addStudent() {

        ArrayList<Student_Quizes> students = new ArrayList<>();

        Scanner in = new Scanner(System.in);
        System.out.println("add student");
        String studentName;
        String Continue;
        int quizScore;
        String quizName;

        boolean addStudents = true;
        boolean addQuiz = true;

        while (addStudents) {

            System.out.println("Student Name");
            studentName = in.next();

            while (addQuiz) {

                System.out.println("Quiz Name");
                quizName = in.next();
                System.out.println("average Score");
                quizScore = in.nextInt();
                students.add(new Student_Quizes(quizName, quizScore));

                System.out.println("Add another Quiz Y/N");
                Continue = in.next();

                if (Continue.equalsIgnoreCase("n")) {
                    addQuiz = false;
                }

            }

            System.out.println("Add another Student Y/N");
            Continue = in.next();

            if (!Continue.equalsIgnoreCase("n")) {

                addQuiz = true;
            } else {
                addStudents = false;
            }

        }

        print(students);

    }

}

这是我的课


package Student_Quizes;

import java.util.ArrayList;

public class Student_Quizes {

    private String studentName;
    private String quizName;
    private int score;
    ArrayList<String> quizNames = new ArrayList<>();
    ArrayList<Integer> quizScores = new ArrayList<>();

    public Student_Quizes() {
        studentName = "";
        quizNames.add("");
        quizScores.add(0);
    }

    public Student_Quizes(String studentName, ArrayList QuizNames, ArrayList quizScores) {
        this.studentName = studentName;
        this.quizNames.add(quizName);
        this.quizScores.add(score);

    }

    public void print() {
        System.out.println("Name:\t\t" + this.studentName);
        System.out.println("Quiz Name:\t" + this.quizNames);
        System.out.println("Quiz Score:\t" + this.quizScores);

    }
}

从那时起,我重新编写了代码现在的代码

这是主要的

包学生

导入java.util.ArrayList; 导入java.util.Scanner;

公共课程Student_main {

public static void main(String[] args) {

    //Create ArrayList of student objects
    ArrayList<Student> students = new ArrayList<>();


    String name;

    boolean addStudent = true;
    String Continue;

    Scanner in = new Scanner(System.in);
    //loop to add multiple students
    while (addStudent) {

        System.out.println("Student Name");
        name = in.next();

        //calls the method to add student information
        addStudents(name, students);

        System.out.println("Would you like to add another Student? Y/N ");
        Continue = in.next();
        //if user does not type n it will continue
        if (Continue.equalsIgnoreCase("n")) {
            addStudent = false;
        }

    }

    System.out.println(students.toString());
}

public static void addStudents(String name, ArrayList<Student> students) {
    //Parralell arrays for quiz names and quiz scores 
    ArrayList<String> quizNames = new ArrayList<>();
    ArrayList<Integer> quizScores = new ArrayList<>();

    boolean addQuiz = true;
    String Continue;
    Scanner in = new Scanner(System.in);
    // Loop to continue adding quizzes
    while (addQuiz) {

        //Method yo add quiz names and scores
        addQuizNames(quizNames);
        addQuizScores(quizScores);

        System.out.println("Would yo like to add another Quiz? Y/N ");

        Continue = in.next();

        if (Continue.equalsIgnoreCase("n")) {
            addQuiz = false;

            // adds the new student passing the students name and quiz info 
            students.add(new Student(name, quizNames, quizScores));

        }
    }

}

public static void addQuizNames(ArrayList<String> quizNames) {

    String quizName;
    Integer quizScore;
    Scanner in = new Scanner(System.in);

    System.out.println("Enter Quiz Name");
    quizName = in.next();
    quizNames.add(quizName);

}

public static void addQuizScores(ArrayList<Integer> quizScores) {

    Integer quizScore;

    Scanner in = new Scanner(System.in);

    System.out.println("Enter Quiz Score");
    quizScore = in.nextInt();
    quizScores.add(quizScore);

}

}

课程 包学生;

导入java.util.ArrayList;

公共班学生{

private String name;
private static ArrayList<String> quizNames = new ArrayList<>();
private static ArrayList<Integer> quizScores = new ArrayList<>();

public Student(String name, ArrayList<String> quizNames, ArrayList<Integer> quizScores) {
    this.name = name;
    Student.quizNames = quizNames;
    Student.quizScores = quizScores;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public static void setQuizNames(ArrayList<String> quizNames) {
    Student.quizNames = quizNames;
}

public static void setQuizScores(ArrayList<Integer> quizScores) {
    Student.quizScores = quizScores;
}

public ArrayList<String> getQuizNames() {
    return quizNames;
}

public ArrayList<Integer> getQuizScores() {
    return quizScores;
}

@Override
public String toString() {
    // adds student info to a formated string
    StringBuilder out = new StringBuilder();

    for (int i = 0; i < quizScores.size(); i++) {
        out.append("\n quiz : ").append(quizNames.get(i)).append("\t\tScore : ").append(quizScores.get(i));
    }
    String finalString = out.toString();
    return "\n\nStudent : " + name + finalString;
}

}

这个问题
我现在遇到的问题是与quizNames和QuizScores。我可以创建许多学生对象,并且每个学生的学生姓名都是正确的,但是每个学生的测验信息都相同。它使用最后一个输入学生的测验信息,因此基本上覆盖了每个学生对象的测验信息。

任何输入表示赞赏,谢谢大家:)


阅读 316

收藏
2020-11-26

共1个答案

小编典典

我建议您使用Map集合和枚举常量。
此外,测验类型和分数是紧密相关的数据,因此它们应该在单独的类别中。

为简单起见,请检查以下代码:

枚举类,用于存储测验的类型。

public enum QuizType {
    SCIENCE, MATHS;
}

QuizResult是一个POJO类,仅用于保存有关测验结果的数据。

public class QuizResult {
    private QuizType quizType;
    private double score;

    public QuizResult(QuizType quizType, double score) {
        this.quizType = quizType;
        this.score = score;
    }

    public QuizType getQuizType() {
        return quizType;
    }

    public void setQuizType(QuizType quizType) {
        this.quizType = quizType;
    }

    public double getScore() {
        return score;
    }

    public void setScore(double score) {
        this.score = score;
    }
}

StudentQuiz类用于输入操作。评论应解释一切。

public class StudentQuiz {

    public StudentQuiz() {
        Map<String, List<QuizResult>> students = processStudentQuizes();
        // Go through the keys of the map (which is the name of students)
        for(String student : students.keySet()) {
            // Get all the quiz results of the student
            List<QuizResult> results = students.get(student);
            System.out.println(student + " ");
            for(QuizResult result : results) {
                // Print the quiz type and the score
                System.out.println(result.getQuizType().name() + " " + result.getScore());
            }
        }
    }

    private Map<String, List<QuizResult>> processStudentQuizes() {
        Map<String, List<QuizResult>> students = new TreeMap<>();

        System.out.println("Add student");
        Scanner s = new Scanner(System.in);

        String answer = null;
        while(!"n".equalsIgnoreCase(answer)) {
            System.out.println("Student Name");
            String studentName = s.next();

            System.out.println("Quiz Name");
            String quizName = s.next();

            // Check if the quiz type actually exist
            boolean quizTypeOk = false;
            for(QuizType type : QuizType.values()) {
                if(type.name().equalsIgnoreCase(quizName)) {
                    // We found the quiz type, so we can break from this loop
                    quizTypeOk = true;
                    break;
                }
            }

            if(!quizTypeOk) {
                // Quiz type couldn't be found, so print the message and start the while loop again
                System.out.println("No such type of quiz! Please start again!");
                continue;
            }

            System.out.println("Average Score");
            double avgScore = s.nextDouble();

            // Now we can create a QuizResult object from the inputed data
            QuizResult result = new QuizResult(QuizType.valueOf(quizName), avgScore);

            // Check if the student already exist
            if(students.containsKey(studentName)) {
                // Add a new result to the list of results for the already existing student
                students.get(studentName).add(result);
            }
            else {
                // Create a new student in the map with a new results list and put the result into the list
                List<QuizResult> results = new ArrayList<>();
                results.add(result);
                students.put(studentName, results);
            }

            System.out.println("Add another Student Y/N");
            answer = s.next();
        }
        s.close();
        return students;
    }

    public static void main(String[] args) {
        new StudentQuiz();
    }
}

我希望这有帮助。

2020-11-26