miminirose 2022-11-24 17:36 采纳率: 100%
浏览 7
已结题

Java字符串分割,存入集合,打印内容

有字符串“小明,男,12,1班;小红女1,小强,男,12,2班"
将字符串分隔,保存到 Student集合中( Student类需求定义),按照年龄降序打印输出每个对象的信息。(字符串转换为整型方法:
Integervalueof(s);)

  • 写回答

1条回答 默认 最新

  • 龙猫爱抓鱼 2022-11-25 17:18
    关注
    
    public static void main(String[] args) {
            String str = "小明,男,12,1班;小红,女,14,3班;小强,男,10,2班";
            String[] strArr = str.split(";");
            List<Student> list = new ArrayList<>();
            for (int i = 0; i < strArr.length; i++) {
                String[] studentArr = strArr[i].split(",");
                Student student = new Student(studentArr[0], studentArr[1], Integer.valueOf(studentArr[2]), studentArr[3]);
                list.add(student);
            }
            list.sort((s1, s2) -> s2.getAge() - s1.getAge());
            for (int i = 0; i < list.size(); i++) {
                System.out.println(list.get(i).toString());
            }
        }
    
    
    //学生类定义
    public class Student {
        private String name;
        private String sex;
        private Integer age;
        private String className;
    
        public Student() {
    
        }
    
        public Student(String name, String sex, Integer age, String className) {
            this.name = name;
            this.sex = sex;
            this.age = age;
            this.className = className;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getSex() {
            return sex;
        }
    
        public void setSex(String sex) {
            this.sex = sex;
        }
    
        public Integer getAge() {
            return age;
        }
    
        public void setAge(Integer age) {
            this.age = age;
        }
    
        public String getClassName() {
            return className;
        }
    
        public void setClassName(String className) {
            this.className = className;
        }
    
        public String toString() {
            return this.name + "," + this.sex + "," + this.age + "," + this.className;
        }
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 12月7日
  • 已采纳回答 11月29日
  • 创建了问题 11月24日

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题