I want to create a program which would be like a home budget, so I have a class AmountModel
(I know that Integer is not so good for id, but it's not a problem now):
import java.time.LocalDate;
public class AmountModel {
private Integer id;
private Double amount;
private CategoryModel categoryModel;
private LocalDate localDate;
// getters/setters etc.
}
And in another class I built this deleteAmount method:
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;
}
Adding object works good, but when I try to use the delete method I have to put first index.
Example:
I have three objects (with index 0, 1, 2).
- When I choose 1 or 2 program do nothing.
- When I choose 0 program deletes first index, remains index 1 and 2.
- When I choose 2, program do nothing.
- When I choose 1, program deletes index 1, remains index 2... etc.
What is wrong with this method?
System.our.printlnand the call tosc.nextInt()to outside of the loop. Otherwise you're asking for the index once for each item in the list.if (am.getId().equals(sc.nextInt())) {This is just not a good idea at so many levels. Do as @Jamie suggests.