英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论