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

为什么我无法接收arraylist的内容

为什么我无法接收arraylist的内容

慕勒3428872 2023-07-13 15:32:57
我目前正在努力修复代码的结果。我应该从菜单添加一个列表,然后显示该列表。但是,我无法检索其内容,而是收到其内存值(我猜?)。学生班    private int number;    private String author;    private String title;    public Student() {    }    public Student(int number, String title, String author) {        this.number = number;        this.title = title;        this.author = author;    }    public int getNumber() {        return number;    }    public String getTitle() {        return title;    }    public String getAuthor() {        return author;    }    public void setNumber(int number) {        this.number = number;    }    public void setTitle(String title) {        this.title = title;    }    public void setAuthor(String author) {        this.author = author;    }    public String ToString() {        return "Number: " + number + "\tTitle: " + title + "\tAuthor: " + author;    }主班import java.util.*;public class Main {    public static void main(String[] args) {        Scanner input = new Scanner(System.in);        ArrayList<Student> newStudents = new ArrayList<Student>();        System.out.println("Please select a number from the options below \n");        while (true) {            // Give the user a list of their options            System.out.println("1: Add a student to the list.");            System.out.println("2: Remove a student from the list.");            System.out.println("3: Display all students in the list.");            // Get the user input            int userChoice = input.nextInt();            switch (userChoice) {                case 1:                    addStudents(newStudents);                    break;                case 2:                    //removeStudent(newStudents);                    break;                case 3:                    displayStudent(newStudents);                    break;            }        }    }输出:1:将学生添加到列表中。2:从列表中删除学生。3:显示列表中的所有学生。3学生@6b2acb7a为什么@6b2babc7a?感谢您的善意帮助和关注。我对编程还算陌生,Java 是我的第一语言。因此,我非常感谢您的帮助和澄清。
查看完整描述

2 回答

?
富国沪深

TA贡献1790条经验 获得超9个赞

当您在 Java 中调用打印任何对象时,toString()会调用该类的内部方法。正如在 Java 中一样,Object 类是所有类的父类,并且toString()方法在 Object 类中可用。所以这个方法对所有Class对象都是可用的。


默认情况下 toString() 对象返回getClass().getName() + '@' + Integer.toHexString(hashCode())。


因此,您将得到Student@6b2acb7a作为输出。如果您想打印其他内容,则需要重写toString()Student 类中的 ,并且return从该方法中获得的任何内容都将得到打印。


Object 类中的方法名为 toString()。所以你需要这样做:


@Override

public String toString() {

        return "Number: " + number + "\tTitle: " + title + "\tAuthor: " + author;

    }

重要提示:当您重写超类中的任何方法时,请使用@Override注释对其进行注释。如果您错误地覆盖它,您将收到编译错误。在编译时发现问题总是比在运行时发现问题更好。如果你这样做了,你就会发现问题了。


查看完整回答
反对 回复 2023-07-13
?
慕容森

TA贡献1853条经验 获得超18个赞

您必须public String toString()在 Student 类中重写以在使用时提供 StringSystem.out.println()

但你已经public String ToString()将其更改为public String toString().

如果没有 outtoString()方法,则将调用from 方法Student,该方法将返回实例的哈希码。toString()java.lang.Object


查看完整回答
反对 回复 2023-07-13
  • 2 回答
  • 0 关注
  • 76 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信