How to calculate sum from user input inside while loop

I got two classes, this one and other called DailyExpenses that’s full of getters and setters + constructors etc..

My problem is that I want to get the sum value of all daily expenses user inputs inside the while loop and print the sum after the program is closed, and I don’t know how to do it.
Here is my code:

import java.util.Scanner;
import java.util.ArrayList;

public class DailyExpensesMain {

public static void main(String[] args) {
    
     ArrayList<DailyExpenses> expenses = new ArrayList<DailyExpenses>();
     Scanner sc = new Scanner(System.in);
     boolean isRunning = true;      
     
         System.out.println("Enter the date for which you want to record the expenses : ");
         String date = sc.nextLine();
        
         while(isRunning) {         
         System.out.println("Enter category: (quit to exit)");  
         String category = sc.nextLine();
         if(category.equalsIgnoreCase("quit")) {   
             break;
         }
        
         System.out.println("Enter price: ");
         double price = sc.nextDouble(); 
         
         sc.nextLine();             
                                    
         System.out.println("Enter details: ");
         String detail = sc.nextLine();
         
        DailyExpenses newExpense = new DailyExpenses(date, category, price, detail);    
         expenses.add(newExpense);                  
        
     }
        
        sc.close();
     for(DailyExpenses u: newExpense) {     
         System.out.println("Date: " + u.getDate() + " Category: " + u.getExpenseCategory() + " Price: " + u.getExpensePrice() + 
                 " Detail: " + u.getExpenseDetail());
     }
     
            
}

I still clueless on the situation

>Solution :

To get the sum of the expenses, you can use a for loop to iterate over the expenses list and add up the price for each expense. Then, you can print the total sum after the loop. Here is an example of how you can do this:

double sum = 0;
for (DailyExpenses expense : expenses) {
    sum += expense.getExpensePrice();
}
System.out.println("The total sum of expenses is: " + sum);

Note that in order to access the getExpensePrice() method, you will need to import the DailyExpenses class at the top of your file. You can do this by adding the following line at the top of your file:

import DailyExpenses;

Also, in the for-each loop at the end of your code, you are using newExpense instead of expenses, which is the name of the list that contains the expenses. You should use expenses instead of newExpense in the for-each loop. Here is how the for-each loop should look like:

for (DailyExpenses u : expenses) {
    System.out.println("Date: " + u.getDate() + " Category: " + u.getExpenseCategory() + " Price: " + u.getExpensePrice() + 
            " Detail: " + u.getExpenseDetail());
}

Leave a Reply