【问题标题】:How can I store a string and two parallel arraylists in an object. (java)如何在一个对象中存储一个字符串和两个并行数组列表。 (爪哇)
【发布时间】:2016-10-20 19:10:15
【问题描述】:

大家好,几天前我问了以下问题,但还是遇到了一些麻烦。

“以下为原帖” 我想存储一个学生姓名,每个姓名都有两个与该姓名关联的 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。我可以制作许多学生对象,每个学生的学生姓名都是正确的,但每个学生的测验信息都是相同的。它使用最后输入的学生的测验信息,因此它基本上会覆盖每个学生对象的测验信息。

感谢大家的任何意见:)

【问题讨论】:

  • 问题是什么?
  • 您永远不应该,永远,永远不会有并行数组列表、并行数组或并行任何数据结构。您应该做的是创建一个带有测验名称和测验分数的测验类。然后,在您的 Student 类中,您有 一个 Quiz 实例列表。
  • @GilbertLeBlanc 是完全正确的。您应该将测验结果存储在 Student 类中,或者创建一个映射,其中键是学生姓名,值是他们拥有的结果列表。

标签: java


【解决方案1】:

一些快速提示:

public class Student_Quizes {
  private String studentName;
  private String quizName; ...

其实是一个好的开始,但是你在这里弄错了:

this.quizNames.add(quizName);
this.quizScores.add(score);

您会看到:您希望您的 Student_Quizes 类允许添加这两条信息。因此:您确实将任何内容放入构造函数的两个列表中。相反,您添加一个类似

的方法
public void addQuizInfo(String name, Integer score) {
  quizNames.add(name);
  quizScores.add(score);
}

到你的班级。然后,您只需使用来自用户的输入继续调用此方法!

您的问题基本上是您“反复”地把事情放在一起。相反,您应该清楚地分开事物。更清楚地说明这一点;您的班级名称已经朝着错误的方向发展。称它为Student ...然后想想学生有什么属性 --- 他有一个名字,然后他列出了他所做的测验。

所以,你首先创建一个学生对象:

Student newStudent = new Student(name);

然后你使用我上面展示的那个方法:

student.addQuiz(quizname, score);

最后:您的代码甚至无法编译。您在 Student_Quizes 中声明您的列表为

ArrayList<String>

例如。这样的列表only 需要字符串。因此,您要添加的代码...另一个 list 根本无效!

最后:你应该使用List、Map等“接口”类型作为类型——你只使用ArrayList等具体的实现类来调用new,比如

List<Integer> scores = new ArrayList<>();

【讨论】:

  • 感谢您如此出色的回应,为我清除了分配:)
  • 非常感谢您的回复,它已经为我解决了所有问题。今晚我累了,但我明天会再做一次,所以我会告诉你我是怎么过的,再次感谢:)
【解决方案2】:

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

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

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

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 类用于输入操作。 cmets应该解释一切。

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

我希望这会有所帮助。

【讨论】:

  • 这是一个很大的帮助,非常感谢,我明天将再次进行适当的尝试,我会告诉你我的进展情况,再次感谢 :)
【解决方案3】:

如果我很好地理解了这个问题,一种解决方案是创建一个新对象的数组列表,而不是

ArrayList quizNames = new ArrayList(); ArrayList quizScores = new ArrayList();

新对象将具有属性 quizScores 和 quizNames,最后在您的类中创建此新对象的列表。

【讨论】:

    猜你喜欢
    • 2013-11-29
    • 2011-08-19
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    • 2015-04-24
    相关资源
    最近更新 更多