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

BookStore类空指针异常求助:作业代码运行测试报错无法定位问题

问题分析与代码修复

嘿,我一眼就瞅见你这段代码里的几个坑,这大概率就是你测试出问题的原因,咱们一步步来捋:

明显的语法错误

你第二个for循环里写了for (Book tempBook : i...,这里的i是个整数变量,根本不是数组/集合,肯定会直接编译失败,应该改成遍历inventory数组才对。

数组初始化的逻辑问题

你一开始把bookTitle初始化为长度0的数组new String[i](此时i=0),虽然后面重新赋值了,但这一步完全没必要,而且如果inventory是空的或者没有匹配的书名,后续操作也容易出问题。

潜在的空指针风险

如果inventory没被初始化(比如构造函数里没给它赋值),或者wordInTitle传入的是null,调用contains方法时会直接抛出空指针异常,得加上防护判断。


修正后的完整代码片段

public class BookStore {
    private String storeName;
    private Book[] inventory;

    // 建议先给BookStore加个构造函数,初始化inventory
    public BookStore(String storeName, Book[] inventory) {
        this.storeName = storeName;
        // 避免外部修改内部数组,这里可以做个拷贝
        this.inventory = inventory != null ? inventory.clone() : new Book[0];
    }

    public String[] getBookTitlesContaining(String wordInTitle) {
        // 先处理wordInTitle为null的情况
        if (wordInTitle == null) {
            return new String[0];
        }
        String lowerCaseWord = wordInTitle.toLowerCase();
        int matchCount = 0;

        // 第一步:统计匹配的书名数量
        for (Book tempBook : inventory) {
            // 同时判断tempBook和title不为null,避免空指针
            if (tempBook != null && tempBook.getTitle() != null 
                && tempBook.getTitle().toLowerCase().contains(lowerCaseWord)) {
                matchCount++;
            }
        }

        // 第二步:创建对应长度的数组并填充数据
        String[] matchedTitles = new String[matchCount];
        int index = 0;
        for (Book tempBook : inventory) {
            if (tempBook != null && tempBook.getTitle() != null 
                && tempBook.getTitle().toLowerCase().contains(lowerCaseWord)) {
                matchedTitles[index++] = tempBook.getTitle();
            }
        }

        return matchedTitles;
    }
}

// 假设Book类的结构是这样的
class Book {
    private String title;
    public String getTitle() { return title; }
    // 其他属性和方法...
}

额外优化建议

  • 可以用ArrayList来代替两次遍历数组,这样更简洁,代码可读性也更高:
public String[] getBookTitlesContaining(String wordInTitle) {
    if (wordInTitle == null) {
        return new String[0];
    }
    String lowerCaseWord = wordInTitle.toLowerCase();
    List<String> matchedList = new ArrayList<>();
    for (Book tempBook : inventory) {
        if (tempBook != null && tempBook.getTitle() != null 
            && tempBook.getTitle().toLowerCase().contains(lowerCaseWord)) {
            matchedList.add(tempBook.getTitle());
        }
    }
    return matchedList.toArray(new String[0]);
}

这样修改后,不管是编译错误还是潜在的运行时异常都解决了,你可以试试跑测试看看效果~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:45:17