You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java如何打印存储在ArrayList中的指定自定义类对象的信息

问题修正说明

核心错误点

  • 未指定ArrayList泛型:你定义的listOfObj是无泛型的裸ArrayList,get()返回的元素默认是Object类型,无法直接调用student类的自定义方法,需要指定泛型为ArrayList<student>明确存储的元素类型。
  • 索引错位:你给用户展示的可选序号是从1开始计数的,但ArrayList的索引从0开始,直接用用户输入的序号取元素会错位,甚至触发索引越界异常,需要将用户输入的数值减1后再作为索引查询。
  • 同文件多public类冲突:Java规范要求单个源文件只能有一个public类,你同时把student和Main都设为public会编译失败,需要去掉student类的public修饰符。
  • Scanner输入缓冲区残留问题:调用nextInt()读取数字后,缓冲区会残留换行符,下一轮循环的nextLine()会直接读取到空值,导致姓名输入异常,需要在每次读取完数字后加一行sc.nextLine()吃掉残留的换行符。

修正后完整代码

import java.util.ArrayList;
import java.util.Scanner;

// 去掉public修饰符,保证单文件只有一个public类
class student{
    String name;
    int age;
    int birthYear;

    public student(String name, int age, int birthYear){
        this.name = name;
        this.age = age;
        this.birthYear = birthYear;
    }
    
    public void printStudentInformation(){
        System.out.println("姓名:"+name);
        System.out.println("年龄:"+age);
        System.out.println("出生年份:"+birthYear);
    }
}

public class Main{
    public static void main(String[] args){
        // 指定ArrayList泛型为student
        ArrayList<student> listOfObj = new ArrayList<>();
        ArrayList<String> names = new ArrayList<>();
        Scanner sc = new Scanner(System.in);

        for(int i = 0; i < 3; i++){
            System.out.println("请输入第"+(i+1)+"位学生信息:");
            System.out.print("姓名:");
            String name = sc.nextLine();
            System.out.print("年龄:");
            int age = sc.nextInt();
            System.out.print("出生年份:");
            int birthYear = sc.nextInt();
            // 吃掉输入数字后残留的换行符
            sc.nextLine();

            student someStudent = new student(name, age, birthYear);
            listOfObj.add(someStudent);
            names.add(name);
        }

        System.out.println("请选择你要查看的学生序号:");
        for(int i = 0; i < names.size(); i++){
            System.out.println((i + 1) + ") " + names.get(i));
        }
        int chosenStudent = sc.nextInt();
        // 序号减1匹配ArrayList从0开始的索引,获取对象后调用打印方法
        listOfObj.get(chosenStudent - 1).printStudentInformation();
        
    }
}

内容的提问来源于stack exchange,提问作者Petetunze

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 07:06:03