Provide the following methods in the ExpenseLedger 1. void addExpense(description, amount): You should be able to figure out the serial of the expense yourself. This method will create an expense item and add it to the ledger 2. int removeSmallExpenses(double amt):This method will find the expense items that are smaller or equal to the amount amt and then remove these items from the list. Note that multiple items can be smaller than this value and thus each of these should be removed. Also this method should return the number of items removed. 3. double totalExpenditure(): This method will calculate the total expenditure recorded in the ledger so far. You can do this by iterating through the expenses list and adding all the amounts to find the total expenditure so far. 4. Override the toString method so that the ledger is printed in a well formatted way
import java.util.ArrayList;
import java.util.LinkedList;
public class ExpenseLedger {
private LinkedList<Expense> expensesLedger;
public ExpenseLedger() {
expensesLedger = new LinkedList<>();
}
void addExpense(String description, double amount) {
expensesLedger.add(new Expense(description, amount));
}
int removeSmallExpenses(double amt) {
ArrayList<Expense> expenses = new ArrayList<>();
for (Expense expense : expensesLedger) {
if (expense.getAmount() <= amt) {
expenses.add(expense);
}
}
for (Expense expense : expenses) {
expensesLedger.remove(expense);
}
return expenses.size();
}
double totalExpenditure() {
double total = 0;
for (Expense expense : expensesLedger) {
total += expense.getAmount();
}
return total;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (Expense expense : expensesLedger) {
builder.append(expense).append('\n');
}
return builder.toString();
}
}
public class Expense {
private String description;
private double amount;
public Expense(String description, double amount) {
this.description = description;
this.amount = amount;
}
public double getAmount() {
return amount;
}
@Override
public String toString() {
return description + " " + amount;
}
}
Comments
Leave a comment