【发布时间】:2020-06-22 15:48:32
【问题描述】:
我想创建一个类似于家庭预算的程序,所以我有一个课程AmountModel
(我知道Integer对id不太好,但现在没问题了):
import java.time.LocalDate;
public class AmountModel {
private Integer id;
private Double amount;
private CategoryModel categoryModel;
private LocalDate localDate;
// getters/setters etc.
}
在另一个类中,我构建了这个deleteAmount 方法:
static Scanner sc = new Scanner(System.in);
public List<amountModel> deleteAmount() {
Iterator<AmountModel> it = amountList.iterator();
while (it.hasNext()) {
System.out.println("Choose index to delete ");
AmountModel am = it.next();
if (am.getId().equals(sc.nextInt())) {
it.remove();
}
break;
}
return amountList;
}
添加对象效果很好,但是当我尝试使用删除方法时,我必须放置第一个索引。
示例:
我有三个对象(索引为 0、1、2)。
- 当我选择 1 或 2 程序时,什么都不做。
- 当我选择 0 时,程序会删除第一个索引,保留索引 1 和 2。
- 当我选择 2 时,程序什么也不做。
- 当我选择 1 时,程序会删除索引 1,保留索引 2...等等。
这个方法有什么问题?
【问题讨论】:
-
将
System.our.println和对sc.nextInt()的调用移到循环之外。否则,您将为列表中的每个项目请求一次索引。 -
我认为您的 sc.nextInt() 调用需要在 while 循环之外,以便比较列表中的每个索引。目前,您每次读取要删除的索引时只比较单个列表项。
-
if (am.getId().equals(sc.nextInt())) {这在很多层面上都不是一个好主意。按照@Jamie 的建议去做。