如何计算存储在 getter 中的值的总和?

huangapple go评论58阅读模式
英文:

How to calculate sum of values stored in getter?

问题

我希望能够计算存储在我的 getter 方法中的整数值的总和。因此,基本上我希望程序执行的操作是将所有工人的总工时相加为一个数字。我不知道如何做到这一点...

这段代码的输出只是所有工人的工时,但没有计算成一个总和。

for(Employee employee : emloyeeArr) {
  if(employee != null) {	            
    System.out.println("所有员工的总工时:" + 
          employee.getEmployeeHours());
  }
}
英文:

I want to be able to calculate the sum of the int values stored in my getter method. So basically what I want the program to do is to sum the total hours of all the workers into one number. I have no idea how to do this...

The output I get with this code is just the hours for all the workers but not calculated into one sum.

for(Employee employee : emloyeeArr) {
  if(employee != null) {	            
    System.out.println("Total hours for all the employees:" + 
          employee.getEmployeeHours());
  }
}

答案1

得分: 0

你可以遍历员工并自行累加工时:

long sum = 0L;
for (Employee employee : emloyeeArr) {
    if (employee != null) {
        sum += employee.getEmployeeHours());
    }
}

或者更方便地,使用流处理:

long sum = Arrays.stream(emloyeeArr)
                 .filter(Objects::notNull)
                 .mapToInt(Employee:getEmployeeHours)
                 .sum();
英文:

You could loop over the employees and sum the hours yourself:

long sum = 0L;
for (Employee employee : emloyeeArr) {
    if(employee != null) {
        sum += employee.getEmployeeHours());
    }
}

Or, more conveniently, with a stream:

long sum = Arrays.stream(emloyeeArr)
                 .filter(Objects::notNull)
                 .mapToInt(Employee:getEmployeeHours)
                 .sum();

答案2

得分: 0

float total_Hours = 0;
for (Employee employee : emloyeeArr) {
    if (employee != null) {
        total_Hours += employee.getEmployeeHours();
    }
}
System.out.println("所有员工的总工时:" + total_Hours);
英文:
float total_Hours = 0;
for(Employee employee : emloyeeArr) {
 if(employee != null) 
 {
  total_Hours += employee.getEmployeeHours();                      
 }
 System.out.println("Total hours for all the employees:" + 
  total_Hours);

All you need to do is run a for loop, get each employee hour and add it in the total then display the total_Hours variable.

huangapple
  • 本文由 发表于 2020年9月3日 00:02:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/63709261.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定