java - 类中的构造函数不能应用于给定类型。希望得到帮助

标签 java constructor bluej

我对 Java 还很陌生,我正在使用 BlueJ。我不断收到错误:

constructor ItemNotFound in class ItemNotFound cannot be applied to given types;
required: int
found: no arguments
reason: actual and formal arguments lists differ in length

我很困惑,也不知道如何解决这个问题。希望有人能帮助我。预先感谢您。

这是我的类(class)目录:

public class Catalog {
    private Item[] list;
    private int size;

    // Construct an empty catalog with the specified capacity.
    public Catalog(int max) {
        list = new Item[max];
        size = 0;
    }

    // Insert a new item into the catalog.
    // Throw a CatalogFull exception if the catalog is full.
    public void insert(Item obj) throws CatalogFull {
        if (list.length == size) {
            throw new CatalogFull();
        }
        list[size] = obj;
        ++size;
    }

    // Search the catalog for the item whose item number
    // is the parameter id.  Return the matching object 
    // if the search succeeds.  Throw an ItemNotFound
    // exception if the search fails.
    public Item find(int id) throws ItemNotFound {
        for (int pos = 0; pos < size; ++pos){
            if (id == list[pos].getItemNumber()){
                return list[pos];
            }
            else {
                throw new ItemNotFound(); //"new ItemNotFound" is the error
            }
        }
    }
}

作为引用,这里还有 ItemNotFound 类 的代码:

// This exception is thrown when searching for an item
// that is not in the catalog.
public class ItemNotFound extends Exception {
    public ItemNotFound(int id) {
        super(String.format("Item %d was not found.", id));
    }
}

最佳答案

ItemNotFound 类只有一个构造函数:一个采用 int 参数的构造函数:

public ItemNotFound(int id)

您尝试在不带任何参数的情况下调用它:

throw new ItemNotFound();

这是行不通的 - 您需要传递该参数的参数。我怀疑你只是想要:

throw new ItemNotFound(id);

(假定 find 方法的 id 参数是您要查找的 ID。)

此外,我建议您重命名异常以包含 Exception 后缀,以遵循 Java 命名约定 - 因此 ItemNotFoundException

需要更改循环 - 目前,如果第一个值没有正确的ID,您就会抛出异常,而您可能想要循环遍历所有这些。因此,您的 find 方法应如下所示:

public Item find(int id) throws ItemNotFoundException {
    for (int pos = 0; pos < size; ++pos){
        if (id == list[pos].getItemNumber()){
            return list[pos];
        }
    }
    throw new ItemNotFoundException(id);
}

关于java - 类中的构造函数不能应用于给定类型。希望得到帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19109545/

相关文章:

c++ - 为什么我无法调用 'explicit a (string x)' ?

c++ - 我应该在构造函数中还是在方法中创建 QLineEdits?

java - BlueJ 的矩形类

java - 无论如何@Inject/@Autowire 一个内部类到一个外部类?

java - 在我的 session 中添加 cookie 时遇到问题

java - netbeans 如何从两个文本字段中获取固定值并将它们添加到带有按钮的第三个文本字段中?

java - 使用动态类引用时抑制警告

php - 如何对构造函数接受一些参数的类的方法进行单元测试?

java - 使用多个线程递增和递减单个共享变量

java - Blue J,我的 listMembers 方法没有从我的数组列表中打印出正确的数据