我到处看,没有见过这样的东西。我对java很新,并且有一个家庭作业。作业是图书馆。它有书籍和DVD,新的和使用过的。我想比较一个对象来确定正确的罚款。
我基本上问这个节目,嘿,这是一本书还是一本DVD?然后嘿,这是一本新书还是DVD,或者这是一本较旧的书。
public double isLate(LocalDate argDateCheckedOut, LIBRARYMATERIALS argMaterial)
{
LocalDate dateCheckedIn = LocalDate.now();
double diff=ChronoUnit.DAYS.between(argDateCheckedOut, dateCheckedIn);
double fine = 0;
if(argMaterial.equals(BOOK))
{
//calculate fine for book
if(argMaterial.getisNew() == true)
{
if(diff > 21)
{
fine = 1 + .25*diff;
}
}
else if(argMaterial.getisNew() == false)
{
if(diff > 28)
{
fine = .25 * diff;
}
}
}
else if(argMaterial.equals(DVD))
{
//calculate fine for dvd
if(argMaterial.getisNew() == true)
{
if(diff > 3)
{
fine = 5 + diff;
}
}
else if(argMaterial.getisNew() == false)
{
if(diff > 7)
{
fine = diff;
}
}
}
return fine;
}
答案 0 :(得分:1)
我会考虑以不同的方式接线。我为Book和DVD创建了一个父类或接口(比如名为" LibraryResource"),这是一个公共双getFine()方法,也许是抽象的,然后我就有了Book和DVD覆盖父方法。让对象计算自己的罚款而不是让自己变得困难。
例如,如果您有这样的父类:
public class Book extends LibraryResource {
private static final long SHORT_OVER_DUE_DIFF = 21;
private static final long LONG_OVER_DUE_DIFF = 28;
public Book(LocalDate checkOutDate, boolean newResource) {
super(checkOutDate, newResource);
}
@Override
public double calculateFine() {
double fine = 0.0;
LocalDate dateCheckedIn = LocalDate.now();
long diff = ChronoUnit.DAYS.between(getCheckOutDate(), dateCheckedIn);
if (isNewResource()) {
if (diff > SHORT_OVER_DUE_DIFF) {
fine = 1 + 0.25 * diff;
} else if (diff > LONG_OVER_DUE_DIFF) {
// .... ??
}
} else {
// else it is NOT new
if (diff > SHORT_OVER_DUE_DIFF) {
// .... ??
} else if (diff > LONG_OVER_DUE_DIFF) {
fine = 0.25 * diff;
}
}
return fine;
}
}
然后Book和Dvd都有自己的公式来计算罚款。例如,Book类看起来像:
{{1}}
答案 1 :(得分:0)
在通过电子邮件与我的教授交谈后,我发现了一个简单的解决方案我相信你的答案会有效但我正在寻找更多......更简单的解决办法。
在这里。我们使用instanceof来比较对象,罚款相应地工作。
double fine = 0;
if(argMaterial instanceof BOOK)
{
//calculate fine for book
if(argIsNew == true)
{
if(diff > 21)
{
fine = 1 + .25*diff;
}
}
else if(argIsNew == false)
{
if(diff > 28)
{
fine = .25 * diff;
}
}
}
else if(argMaterial instanceof DVD)
{
//calculate fine for dvd
if(argIsNew == true)
{
if(diff > 3)
{
fine = 5 + diff;
}
}
else if(argIsNew == false)
{
if(diff > 7)
{
fine = diff;
}
}
}
return fine;