英文:
Decrement a value from an existing array if a condition has met using a method - OOP
问题
以下是您要求的翻译内容:
我正在尝试为一个图书馆练习创建一个方法,但是我在方法 RentBook() 中遇到了一些问题。
基本上,我使用一个方法来添加我想租借的书籍,但是当我使用我的代码时,库存减少了-1,而不是所选择的那本书。
代码:
public String rentBook(Book book) {
for (int i = 0; i < books.length; i++) {
if ((books[i].equals(book)))
inStock[i]--;
}
return "book name" + book;
}
}
我的 equals 函数:
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Book other = (Book) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (Double.doubleToLongBits(price) != Double.doubleToLongBits(other.price))
return false;
return true;
}
我的结果:
[11, 39, 43, 1, 12, 3]
我想要的:
[12, 39, 44, 2, 13, 4]
英文:
I am trying to create a method for a LIBRARY exercise, however, I have some issues with the method
RentBook().
Basically, I use to a method to add a book that I want to rent, when using my code it decrements -1 all stocks instead of the one is chosen.
code:
public String rentBook(Book book) {
for (int i = 0; i < books.length; i++) {
if ((books[i].equals(book)))
inStock[i]--;
}
return "book name" + book;
}
}
my equals function:
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Book other = (Book) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (Double.doubleToLongBits(price) != Double.doubleToLongBits(other.price))
return false;
return true;
}
what I get:
[11, 39, 43, 1, 12, 3]
What I want:
[12, 39, 44, 2, 13, 4]
答案1
得分: 1
尝试调试您的程序。
- 在
equals
方法中添加一些打印语句,以打印您要比较的两本书,以查看这是否是您想要进行比较的方式?在逻辑的不同位置打印它们,并进行相应的标记。 - 使用一些特制的
book
对象来测试各种equals
条件。 - 并且在每次减少库存后打印
instock
值。
其中一个最好的调试工具是 print
语句。请大量使用它。
英文:
Try debugging your program.
- Put some print statements in the
equals
method to print the two books you are comparing to see if that is how you want to compare? Print them at different locations in the logic and label them accordingly. - Use some specially made
book
objects to test variousequals
conditions. - And print the
instock
values after each decrement is made.
One of the best debugging tools around is the print
statement. Use it liberally.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论