我正在尝试删除输入名称的地址簿条目,但我得到了 java:148错误:不兼容的类型 return fileToDelete.delete();
required: AddressBookEntry
found: boolean
1错误
有问题的代码是:
public class AddressBookDelegateImpl implements AddressBookDelegate {
private File userHomeDir;
private File addressBookDirectory;
private String replaceSpacesWithUnderScores( String string ) {
return string.replaceAll( " ", "_" ).toLowerCase();
}
public AddressBookEntry deleteAddressBookEntry( String name )
throws AddressBookDelegateException {
try{
String dname = replaceSpacesWithUnderScores( name );
File fileToDelete = new File( addressBookDirectory, dname );
return fileToDelete.delete() ;
} catch(NullPointerException e) {
throw new AddressBookDelegateException("Could not find the file", e);
}
}
}
答案 0 :(得分:2)
您的方法在其声明中返回并AddressBookEntry
:
public AddressBookEntry deleteAddressBookEntry( String name )
而return语句说:
return fileToDelete.delete() ;
您可能需要考虑将AddressBookEntry
返回类型声明为boolean
,如下所示:
public boolean deleteAddressBookEntry( String name )
答案 1 :(得分:0)
File.delete()
返回一个布尔值...
答案 2 :(得分:0)
错误已经很好地描述了它。如果删除成功, delete 方法返回一个布尔值。因此,如果返回值为true,则应检查该值,然后返回已删除的AddressBookEntry。
答案 3 :(得分:0)
在Java中,方法的返回类型在方法声明中定义。 所以在你的例子中,你有:
public AddressBookEntry deleteAddressBookEntry( String name )throws AddressBookDelegateException {
try{
String dname = replaceSpacesWithUnderScores( name );
File fileToDelete = new File( addressBookDirectory, dname );
return fileToDelete.delete() ; //this returns a boolean
} catch(NullPointerException e) {
throw new AddressBookDelegateException("Could not find the file", e);
}
}
因此,如果您不想更改返回方法,这可能就是您想要做的,那么您应该尝试使用此代码:
public boolean deleteAddressBookEntry( String name )throws AddressBookDelegateException {
try{
String dname = replaceSpacesWithUnderScores( name );
File fileToDelete = new File( addressBookDirectory, dname );
return fileToDelete.delete() ; //this returns a boolean
} catch(NullPointerException e) {
throw new AddressBookDelegateException("Could not find the file", e);
}
}
这将返回fileToDelete.delete()
方法的结果。
答案 4 :(得分:0)
请修改你的方法deleteAddressBookEntry,如下所示:
public Boolean deleteAddressBookEntry(String name)
throws AddressBookDelegateException {
try {
String dname = replaceSpacesWithUnderScores(name);
File fileToDelete = new File(addressBookDirectory, dname);
if(fileToDelete.exists())
return fileToDelete.delete();
} catch (NullPointerException e) {
throw new AddressBookDelegateException("Could not find the file", e);
}
return false;
}