我对 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/