自制链表薪资查询返回0,数据结构未达预期结果
问题:自定义链表getPay方法查询薪资始终返回0
我正在开发一款预算工具,实现了一个存储各类收入信息的自定义链表,但调用getPay方法查询某份工作的薪资时,返回结果始终为0。
我的IncomeNode类代码:
public class IncomeNode{ Node head; int size; public IncomeNode(){ head = null; size = 0; } class Node{ double amount; String jobName; Node next; Node(String name, double number){ jobName = name; amount = number; } Node(){ jobName = ""; amount = 0; } } public void add(String name, double number){ Node newIncome = new Node(name, number); if(head == null){ head = newIncome; } else{ Node current = head; while(current.next != null){ current = current.next; } current.next = newIncome; } size++; } public double getPay(String job){ Node current = head; while(current.next !=null){ if(current.jobName.equals(job)){ return current.amount; } current = current.next; } return 0; } }
调用代码片段:
class Budget{ public static void main(String[] args){ Scanner scnr = new Scanner(System.in); boolean newJob = true; if(payType.equals("variable")){ System.out.print("What is your hourly pay?"); double wage = scnr.nextDouble(); System.out.print("How many hours do you work a week?"); double hours = scnr.nextDouble(); IncomeNode jobs = new IncomeNode(); jobs.add(name, wage * hours); System.out.println(jobs.getPay(name)); System.out.print("Do you want to add another income?"); if(scnr.next().equals("no")){ newJob = false; } } } }
问题原因
getPay方法的遍历逻辑存在漏洞:循环条件使用current.next != null,会导致最后一个节点永远不会被检查。
比如你测试的场景:只添加了一个工作节点时,head就是这个节点,current.next为null,循环体直接不执行,程序直接走到return 0,所以返回结果始终是0。
修复方案
把循环条件改为current != null,确保遍历链表中的每一个节点:
public double getPay(String job){ Node current = head; // 遍历所有节点,直到current为null(链表末尾) while(current != null){ if(current.jobName.equals(job)){ return current.amount; } current = current.next; } return 0; }
额外优化(可选)
为避免空指针异常(比如job为null,或某个节点的jobName为null),可以调整equals调用顺序并增加空值判断:
public double getPay(String job){ if(job == null) return 0; Node current = head; while(current != null){ // 把job放在equals前面,避免current.jobName为null时抛出异常 if(job.equals(current.jobName)){ return current.amount; } current = current.next; } return 0; }
内容的提问来源于stack exchange,提问作者Jcaro213
相关产品推荐
相关产品推荐

