java get average for all items in a selected category

后端 未结 1 1982
天命终不由人
天命终不由人 2021-01-29 12:19

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

相关标签:
1条回答
  • 2021-01-29 12:32

    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.

    0 讨论(0)
提交回复
热议问题