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

Java实现自增bookID输出图书信息的Book数组代码编写问题

Java图书录入与输出功能实现修正

现存问题梳理

  • Book类ID自增逻辑错误:bookID为实例属性,每次创建对象都会重置为1000,静态变量nextID的使用不符合自增需求
  • main方法输入逻辑错误:Scanner类不存在nextBook()方法,录入顺序有误,缺少最终遍历输出的逻辑

修正后完整代码

import java.util.Scanner;

class Book{
    // 实例属性:当前图书ID
    private Integer bookID;
    // 静态属性:全局共享的下一个可用ID,初始值为1000
    static Integer nextID = 1000;
    private String title;
    private String author;
    private boolean isBorrowed;
    
    public Book(String title, String author){
        this.title = title;
        this.author = author;
        this.isBorrowed = false;
        // 赋值当前可用ID,再自增更新下一个可用ID
        this.bookID = nextID++;
    }
    
    public void borrowBook(){
        isBorrowed = true;
    }
    
    public void returnBook(){
        isBorrowed = false;
    }
    
    public boolean isBookBorrowed(){
        return isBorrowed;
    }
    
    public void show() {
        System.out.println("Book ID: " + bookID);
        System.out.println("Title: " + title);
        System.out.println("Author: " + author);
        System.out.print("Status: ");
        if (isBorrowed)
            System.out.println("Not Available");
        else
            System.out.println("Available");
        System.out.println();
    }
}

public class MyClass {
    public static void main(String args[]) {
       Scanner input=new Scanner(System.in);
       System.out.print("请输入图书总数:");
       int num=input.nextInt();
       input.nextLine(); // 吃掉数字输入后的换行符
       
       Book[] books = new Book[num];
       String title;
       String author;
       for (int i=0; i<num; i++) {
           System.out.print("请输入第"+(i+1)+"本图书的书名:");
           title = input.nextLine();
           System.out.print("请输入第"+(i+1)+"本图书的作者:");
           author = input.nextLine();
           // 创建图书对象存入数组
           books[i] = new Book(title, author);
       }
       // 遍历输出所有图书信息
       System.out.println("\n所有图书信息如下:");
       for (Book book : books) {
           book.show();
       }
       input.close();
    }
}

核心修改说明

  • 调整ID自增逻辑:将ID基数设置为全局共享的静态变量,每次创建实例时赋值当前ID后自增,保证ID从1000开始连续不重复
  • 修正输入逻辑:按顺序读取书名、作者后再实例化Book对象存入数组,符合用户录入习惯
  • 新增遍历输出逻辑:所有图书录入完成后遍历数组调用show()方法,输出要求的所有字段信息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 14:15:06