简体   繁体   English

访问数组列表中的元素(Java)

[英]Accessing an element in an arraylist (Java)

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 .我一直在尝试通过我一直在研究的代码获得薪水,这样我就可以计算出tax = tsalary Unfortunately, I've hit a bump ever since I was trying to access the salary from my ArrayList .不幸的是,自从我试图从我的ArrayList获取薪水以来,我遇到了一个障碍。 I tried getting the salary via salary = li.next().getSalary();我尝试通过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 + ".");
            }

As mentioned by @JustAnotherDeveloper in comments,the problem lies here.正如@JustAnotherDeveloper 在评论中提到的那样,问题出在此处。

EmployeeRecords e = li.next();
salary = li.next().getSalary();

Iterator.next() always returns the next element in the iteration and moves the pointer to it. Iterator.next()总是返回迭代中的下一个元素并将指针移动到它。

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.您已经使用li.next()获取了对象,现在如果您再次调用li.next() ,它将返回并移动到列表中的下一个对象。 Thus you will never get the desired output.因此,您将永远无法获得所需的输出。

Usage of next() twice seems to be the problem.使用 next() 两次似乎是问题所在。 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 each 循环(如果可以使用 for each 迭代“al”)

for(EmployeeRecords e : al) {
    salary = e.getSalary();
    long currentEmpNo = e.getEmployeeNum();
    if (currentEmpNo == empNo) {
        // and the rest of the code
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM