为了账号安全,请及时绑定邮箱和手机立即绑定

如何覆盖它以获得结构化的方式

如何覆盖它以获得结构化的方式

慕森王 2022-05-12 17:25:07
我正在使用 Maps 集合创建学生管理简单的 java 项目,其中 id 是我的密钥,名称、标记和手机号码。是地图的值。那么如何以结构化的方式打印它。HashMap<Integer, LinkedHashSet<StudentCinstructor>> st = new HashMap<>();LinkedHashSet<StudentCinstructor> st2 = new LinkedHashSet<>();Scanner sc = new Scanner(System.in);public void add() {    System.out.println("enter the name of the student");    String name = sc.nextLine();    System.out.println("enter the marks of the student");    double marks = sc.nextDouble();    System.out.println("enter the mobile number of the student");    long mobile_no = sc.nextLong();    st2.add(new StudentCinstructor(name, marks, mobile_no));    System.out.println("enter the unique id of the student");    int id = sc.nextInt();    st.put(id, st2);当我尝试在主方法中打印自定义类时,它给了我一个带有哈希码的地址。“HashmapDemo.MethodsForManagement@3d4eac69”
查看完整描述

2 回答

?
蓝山帝景

TA贡献1843条经验 获得超7个赞

两个备注:

1-当您尝试打印对象StudentCinstructor时,如果没有专门的toString()方法,您将无法获得结构良好的输出。因此,您需要做的是toString()为您的类编写一个方法,然后您可以打印到控制台。例子 :

public static String toString() {
     return "Customize here + Put this method inside your class";
     }

2-我不明白您为什么要使用LinkedHashSet存储StudentCinstructor对象然后将此 HashSet 存储在地图中,而不是创建StudentCinstructor对象并将其直接存储在地图中,如果所有学生都有唯一的 id。如 :

HashMap<Integer, StudentCinstructor> st = new HashMap<>();


查看完整回答
反对 回复 2022-05-12
?
猛跑小猪

TA贡献1858条经验 获得超8个赞

查看您的打印输出“HashmapDemo.MethodsForManagement@3d4eac69”,您似乎正在打印 class 的对象HashmapDemo.MethodsForManagement。如果要打印 的对象StudentCinstructor,则需要将该对象传递给 print 方法,例如System.out.println(student);.


你需要重写类中的toString()方法StudentCinstructor。(即把下面的代码放在StudentCinstructor课堂上。)


( name,marks并且mobile_no在下面的代码中是StudentCinstructor类中的字段。)


  @Override

  public String toString()

  {

    return "Name=" + name + ", Marks=" + marks + ", Mobile number=" + mobile_no;

  }


查看完整回答
反对 回复 2022-05-12
  • 2 回答
  • 0 关注
  • 190 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号