小编典典

Java获取所选类别中所有项目的平均值

java

如何获得所选公司中所有员工的平均工资?我首先选择公司,然后传递ID,然后基于该ID,我将所有员工都带到那里并将其信息显示在表格中。目标是获得该组中每个人的平均工资。

<%@page import="data.Employee"%>
<%@page import="data.Company"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<jsp:useBean id="company" type="data.Company" scope="request"/>



<% 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 ::: This is working based on JChris's answer
<p>Average salary of all employees in this company:<%=sum/(double)employees.size()%> </p>
//this is returning zero.       
<p> New average method: <%=company.getAverageSalary()%></p>

阅读 284

收藏
2020-12-03

共1个答案

小编典典

您可以将薪金加起来,然后除以雇员数:

<% 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>

话虽如此,我敦促您在走那条路之前重新考虑。如果JSP内的代码超过1-2页,将严重阻碍您对其进行维护的机会。您的所有业务逻辑都应在代码中(例如,在Servlet中)发生,并且在JSP中仅显示信息。

2020-12-03