someangular someangular - 4 years ago 107
Java Question

java get average for all items in a selected category

How can I get the average salary of all employees in the selected company?
I first select the company and then pass the id and based on that id, i get all employees in there and display their info in a table. The goal is to get the average salary of everyone in this group.

<% List<Employee> employees = company.getEmployees();%>
<table border="1">

<tr>
<td>ID</td>
<td>Name</td>
<td>Salary</td>
</tr>
<%
for(int i=0; i <employees.size(); i++){
%>
<tr>
<td><%=employees.get(i).getId()%></td>
<td><%=employees.get(i).getNom()%></td>
<td><%=employees.get(i).getSalary()%></td>
</tr>
<% } %>
</table>

//get the average salary of all employees
<p>Average salary of all employees in this company: <%=employees.get(0).getSalary()%> </p>

Answer Source

You could sum the salaries up and then divide by the number of employees:

<% List<Employee> employees = company.getEmployees();
   double sum=0.0;
%>
<table border="1">

    <tr>
        <td>ID</td>
        <td>Name</td>                        
        <td>Salary</td>             
    </tr>        
    <%
for(int i=0; i <employees.size(); i++){
    sum += employees.get(i).getSalary();
%> 
        <tr>      
            <td><%=employees.get(i).getId()%></td>
            <td><%=employees.get(i).getNom()%></td>                
            <td><%=employees.get(i).getSalary()%></td>  
        </tr>
    <% } %>
</table> 

//get the average salary of all employees
<p>Average salary of all employees in this company:<%=sum/(double)employees.size()%> </p>

Having said that, I urge you to reconsider before going down that road. Having code inside your JSP will severely hinder your chances of maintaining it if it gets any bigger than 1-2 pages. All your business logic should happen in your code (e.g. inside your servlets) and in JSPs only display the information.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download