我必须遍历两个数组并计算匹配的雇员姓名的薪水总额。我有两个数组:empData:[Emp1,Emp2]和 salData:[[name:Emp1,sal:1000],[name:Emp2,sal:5000],[name:Emp1,sal:6000],[name:Emp1,sal:7000]]。我必须遍历empData还有salData,并计算匹配的emp名称的薪水总和,然后将用户名和相应的sal都推入数组。
double total
empData.each{x ->
sapData.each{ y ->
if(y.name == x)
{
total =total + y.sal;
}
}
但是出现错误无法将类为'java.lang.String'的对象'null1000.0'强制转换为类'java.lang.Double'。如果我将total声明为字符串,则结果为sal的串联。
答案 0 :(得分:1)
您没有将total
初始化为任何东西。您的薪水值实际上也可能是字符串;很难从您提供的内容中分辨出来。
将total
初始化为0,并在必要时确保将y.sal
强制翻倍。
答案 1 :(得分:0)
呃,循环又循环……看看Groovy的收集方法。
// poor emp3 has no salaryData
def employeeNames = ['emp1', 'emp2', 'emp3']
def salaryData = [[name: 'emp1', sal: 1000], [name: 'emp2', sal: 5000], [name: 'emp1', sal: 6000], [name:'emp1', sal: 7000]]
// here's our output array variable
def output = []
// for each employee
// find all the salaryData elements where salaryData.name == employeeName
// using that list, collect just the salary value
// using that list, sum it, adding to an initial value of 0
// append a new entry in output containing the name, and total salary
employeeNames.each { employeeName ->
output << [name: employeeName, totalSalary: salaryData.findAll { sal -> sal.name == employeeName }.collect { sal -> sal.sal }.sum(0)]
}
println output
groovyconsole产量: [[name:emp1,totalSalary:14000],[name:emp2,totalSalary:5000],[name:emp3,totalSalary:0]]