** I am not sure how to get the sum of certain elements from a hashset please help** i need to add the amount from the expense
i am not sure about the line - System.out.println("Total Amount Spent:"+ set1.addAll([1]);
This is my code and the required output is also give below:
import java.util.*;
class Expense implements Comparable<Expense>{
String expenseCategory;
Integer amount;
public String getExpenseCategory() {
return expenseCategory;
}
public void setExpenseCategory(String expenseCategory) {
this.expenseCategory = expenseCategory;
}
public Integer getAmount() {
return amount;
}
public void setAmount(Integer amount) {
this.amount = amount;
}
public Expense(String expC , Integer amount) {
this.expenseCategory=expC;
this.amount = amount;
}
public String toString() {
return expenseCategory+ " " +amount;
}
public int compareTo(Expense e) {
if(amount>e.amount){
return 1;
}else if(amount<e.amount){
return -1;
}else{
return 0;
}
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
TreeSet<Expense> set1 = new TreeSet<Expense>();
while(true) {
System.out.println("Enter expense category");
String expC = sc.next();
System.out.println("Enter expense amount");
String amt = sc.next();
set1.add(new Expense(expC,Integer.valueOf(amt)));
System.out.println("Do you want to continue(yes/no):");
String cond = sc.next();
if(cond.equals("no")) {
break;
}
}
System.out.println("Top spending categories");
System.out.println("Category Amount");
Iterator x = set1.descendingIterator();
while(x.hasNext()) {
System.out.println(x.next());
}
System.out.println("Total Amount Spent:"+ set1.addAll([1]);//please help me figure out this part
}
}
OUTPUT Should be like:
Enter expense category
Rent
Enter expense amount
6000
Do you want to continue(yes/no):
yes
Enter expense category
Food
Enter expense amount
4500
Do you want to continue(yes/no):
yes
Enter expense category
Travel
Enter expense amount
2300
Do you want to continue(yes/no):
yes
Enter expense category
Mobile
Enter expense amount
700
Do you want to continue(yes/no):
no
Top spending categories
Category Amount
Rent 6000
Food 4500
Travel 2300
Mobile 700
Total amount spent: 13500
Temporarly i added : a int variable in main class which will sum up the values every time i enter the amount and display it at the end.