I've been trying to get the salary on the code I've been working on so I can compute the salary after tax = tsalary
. Unfortunately, I've hit a bump ever since I was trying to access the salary from my ArrayList
.
I tried getting the salary via salary = li.next().getSalary();
but when I run it, I get an output not on that certain employee number I'm trying to compute.
Even hints of it will be plenty helpful. Thank you
case 5:
found = false;
double tsalary = 1;
System.out.print("Enter Employee Number: ");
empNo = sc.nextInt();
li = al.listIterator();
while (li.hasNext()){
EmployeeRecords e = li.next();
salary = li.next().getSalary();
if (e.getEmployeeNum() == empNo) {
if (salary >= 20001) {
tsalary = salary * 0.75;
} else {
tsalary = salary * 0.80;
}
found = true;
}
}
if(!found){
System.out.println("Record not available / found.");
} else {
System.out.println(empNo " " name "'s salary after tax is " tsalary ".");
}
CodePudding user response:
As mentioned by @JustAnotherDeveloper in comments,the problem lies here.
EmployeeRecords e = li.next();
salary = li.next().getSalary();
Iterator.next()
always returns the next element in the iteration and moves the pointer to it.
You have already fetched the object using li.next()
, now if you call li.next()
again it will return and move to the next object from the list. Thus you will never get the desired output.
CodePudding user response:
Usage of next() twice seems to be the problem. You can try,
EmployeeRecords e = li.next();
salary = e.getSalary();
Or not using iterator and by using for each loop (if "al" can be iterated using for each)
for(EmployeeRecords e : al) {
salary = e.getSalary();
long currentEmpNo = e.getEmployeeNum();
if (currentEmpNo == empNo) {
// and the rest of the code
}
}