我是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
我很困惑,反过来又不确定如何解决这个问题。希望有人可以帮助我。提前谢谢。
这是我的课程目录:
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
}
}
}
}
供参考,以下是class 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));
}
}
答案 0 :(得分:3)
ItemNotFound
类只有一个构造函数:一个带有int
参数的构造函数:
public ItemNotFound(int id)
你试图在没有任何争论的情况下调用它:
throw new ItemNotFound();
这不会起作用 - 您需要传递该参数的参数。我怀疑你只是想要:
throw new ItemNotFound(id);
(假设id
方法的find
参数是您要查找的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);
}
答案 1 :(得分:2)
您为类ItemNotFound
提供了一个自定义构造函数,并且在您使用它时不传递必需的参数。
尝试在此处传递必需的参数
throw new ItemNotFound(id);
所以你的代码变成了
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(id); // Now constructor satisfied
}
}
}
并且
throw new ItemNotFound();
当您的班级ItemNotFound
类似
// This exception is thrown when searching for an item
// that is not in the catalog.
public class ItemNotFound extends Exception {
public ItemNotFound() {
super("Sorry !! No item find with that id"); //Now a generic message.
}
}
答案 2 :(得分:0)
throw new Item()无效,因为已经定义了显式构造函数Item(int id)。
答案 3 :(得分:0)
您提供的构造函数没有任何参数。
public ItemNotFound()
并且您正在调用new ItemNotFound(id)
,而在创建类ItemNotFound的实例时需要one parameter of type int
的构造函数。所以你需要一个重载的构造函数
public class ItemNotFound extends Exception {
public ItemNotFound() {
super("Sorry !! No item find with that id"); //Now a generic message.
}
public ItemNotFound(int if) {
this(); //Since you are not using any int id in this class
}
}