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

Java中如何访问数组内对象的指定成员变量?

解决Book数组元素的printf格式化输出问题

嘿,我来帮你搞定这个printf格式化输出的问题!其实核心就是正确访问数组中Book对象的成员变量,下面一步步给你讲清楚:

核心原理

数组里的每个元素都是Book对象,所以你只需要用数组名[索引].成员变量名的方式,就能获取到指定元素的指定属性值——前提是这个成员变量是可访问的(比如public修饰,或者你给它写了对应的getter方法)。

代码示例

首先先补全你的Book类定义(我修正了代码里书名和作者的小错误,更贴合实际):

class Book {
    // 这里先用public演示,实际开发建议用private+getter的封装写法
    public String title;
    public String author;
    public int pages;

    // 构造方法
    public Book(String title, String author, int pages) {
        this.title = title;
        this.author = author;
        this.pages = pages;
    }

    // 如果用private修饰变量,就需要这些getter方法(推荐写法)
    // public String getTitle() { return this.title; }
    // public String getAuthor() { return this.author; }
    // public int getPages() { return this.pages; }
}

然后在你的BookReport类里,就可以这样用printf格式化输出了:

public class BookReport {
    public static void main(String[] args){
        Book[] TheBooks = new Book[5];
        TheBooks[0] = new Book("Gone With The Wind", "Margaret Mitchell", 1037);
        TheBooks[1] = new Book("1984", "George Orwell", 328);
        TheBooks[2] = new Book("To Kill a Mockingbird", "Harper Lee", 336);
        TheBooks[3] = new Book("Pride and Prejudice", "Jane Austen", 432);
        TheBooks[4] = new Book("The Great Gatsby", "F. Scott Fitzgerald", 180);

        // 输出单个元素的指定属性
        System.out.printf("第一本书:书名《%s》,作者%s,共%d页%n",
            TheBooks[0].title,
            TheBooks[0].author,
            TheBooks[0].pages);

        // 如果用了getter方法,就改成这样调用
        // System.out.printf("第一本书:书名《%s》,作者%s,共%d页%n",
        //     TheBooks[0].getTitle(),
        //     TheBooks[0].getAuthor(),
        //     TheBooks[0].getPages());

        // 遍历整个数组,格式化输出所有书籍信息
        System.out.println("\n=== 全部书籍列表 ===");
        for (int i = 0; i < TheBooks.length; i++) {
            System.out.printf("第%d本:《%s》 - %s,%d页%n",
                i+1,
                TheBooks[i].title,
                TheBooks[i].author,
                TheBooks[i].pages);
        }
    }
}

关键说明

  • printf的格式符要和变量类型匹配:%s对应字符串,%d对应整数,%n是跨平台的换行符(比\n更友好)
  • 如果你的Book类成员变量是private修饰的(这是Java的最佳实践),一定要用对应的getter方法来获取属性值,不能直接访问变量
  • 数组索引从0开始,所以TheBooks[0]是第一个元素,TheBooks[4]是第五个元素

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:27:51