当前位置: 首页 > 面试题库 >

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

班高明
2023-03-14
问题内容

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

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

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


问题答案:

我建议您使用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();
    }
}

我希望这有帮助。



 类似资料:
  • 我不确定我是否在做这件事是正确的,我一整天都在尝试这件事,我很困惑,有没有人能给我一些建议,让我能更好地做这件事。 很抱歉,如果我的问题是混乱的,我想程序会这样运行。 输入学生姓名 80 是否添加其他测验? Y 学生姓名:乔 小测验名称:理科,分数60分 我的代码现在到处都是,但我会把我有的贴出来。 公开课Student_main{ } 班级打包学生;

  • 问题内容: 我写了一个程序,给我三个数组。一个字符串数组和两个dole数组…。但是我想将它们保存在一件事中(我不知道它是数组还是矩阵)。 。 例如:我有一个文件要读取,输入内容如下: 我已经制作了三个数组,一个数组存储字符串的名称,另外两个数组存储双打的两列… 但是我想将整行“(apple 2.3 4.5)”存储在一件事中,这样,如果我想找到苹果,我也可以获得apple的相关值.....能否请大家

  • 如何在一个对象中存储对象和数组?更新一个对象内的对象和数组 const obj={key1:1,key2:2,key3:3,keys:['key1','key2','key3']};我在一次采访中得到了这个问题。现在我想在对象中添加一些新数据。2无论何时添加到对象中,都应在该主对象内的数组中更新“key_”(添加了key number)。 输出应该是这样的(你可以使用任何方法/函数/循环来更新它.

  • 问题内容: 我是一个自学者。当前,我正在制作一个需要矩阵型数据库的GUI项目。 我想学习如何创建一个可以在arraylist中存储多个对象的类。 这是我的示例代码。请注意,这只是我的尝试。该代码尚未完成,因此无法正常工作。 谢谢你的热心帮助。 }} 问题答案: 我认为一种更好的方法是创建一个用户信息类来存储特定用户的信息。 然后将其放入ArrayList中。 然后,对于您当前的方法,您可以

  • 这是第一个代码: 那么这是它将在其中显示输出的主类: 很抱歉,如果我不清楚我的问题,但我想使用ArrayList,其中我将ArrayList存储在Person类中,我想使用公共字符串toString查看它,这样它将显示名称和年龄