如何在一个对象中存储一个字符串和两个并行的arraylistjava

如何解决如何在一个对象中存储一个字符串和两个并行的arraylistjava

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

我希望这有帮助。

解决方法

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

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res