如何搜索 Java 链表

How do I search through a Java Linked List

我正在为我的介绍 Java class 完成我的最后一个作业。我们正在做一个链接列表(我们自己构建)库存程序。我的 findItem 方法有问题。我将如何按项目编号搜索我的链接列表?我这样做的方式有效,但我需要摆脱休息。我的导师说我 "need to set a compound condition, the !found you have and the not null." 我已经尝试了几种不同的变体,但还是做不到。请提供任何帮助、建议或示例,我们将不胜感激,这是最后一周,一切都将在明天到期。我的主要问题是在 InventoryLL class 中的 findItem() 中,但我发布了上下文的整个代码。

InventoryLL

import java.util.Scanner;
import java.io.PrintWriter;
import java.io. FileOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class InventoryLL
{
int count = 0;
private ItemNode head;
Scanner scannerObject = new Scanner(System.in);

public InventoryLL()
{
    head = null;
}

public void addItem()
{
    try{
        System.out.print("\nPlease enter name of item: ");
        String lname = scannerObject.nextLine();
        System.out.print("\nPlease enter a brief description of the item: ");
        String ldesc = scannerObject.nextLine();
        System.out.print("\nPlease enter the amount on hand: ");
        int lonHand = scannerObject.nextInt();
        System.out.print("\nPlease enter unit price of the item: $");
        Double lunitPrice = scannerObject.nextDouble();
        ItemNode temp = new ItemNode(count + 1, lname, ldesc, lonHand, lunitPrice);
        count++;
        temp.setNext(head);
        head = temp;
        System.out.println("\nThank you. The ID number for " + lname + " is " + count);
        scannerObject.nextLine();
    }catch(Exception e){    
            System.out.println("\nERROR! Please try again:\n");
            scannerObject.nextLine();
            }   
}

public ItemNode findItem(){
    int inputID;
    boolean found = false;
    ItemNode current = null;
        try{
        System.out.print("\nGreetings, please enter the ID number for item:\n");
        inputID = scannerObject.nextInt();
        scannerObject.nextLine();
            for (current = head; !found; current = current.getNext()){
                if (current.getID() == inputID){
                    found = true;
                    break; // I need to get rid of break
                    }
                }       
            }catch(Exception e)
            {
                System.out.println("\nERROR!");
            }
    return current;
}

public void modify()
{   
    ItemNode current = findItem();
        if (current == null){
        System.out.println("\nInvalid input! Please try again:");
            }else{
        try{
            System.out.print("\nPlease enter name of item: ");
            String lname = scannerObject.nextLine();
            current.setName(lname);
            System.out.print("\nPlease enter a brief description of the item: ");
            String ldesc = scannerObject.nextLine();
            current.setDesc(ldesc);
            System.out.print("\nPlease enter the amount on hand: ");
            int lonHand = scannerObject.nextInt();
            current.setOnHand(lonHand);
            System.out.print("\nPlease enter unit price of the item: $");
            double lunitPrice = scannerObject.nextDouble();
            current.setUnitPrice(lunitPrice);
            scannerObject.nextLine();
        }catch (Exception e)
                {
                System.out.println("\nInvalid command! Please try again: ");
                }
        }
}

public void displayAll()
{   System.out.println("_______________________________________________________________________________\n");    
    System.out.println("                                 Inventory                                     ");
    System.out.println("_______________________________________________________________________________\n");
    System.out.printf("\n%-6s%-20s%-24s%-12s%-6s\n", "ID:", "Name:", "Description:","On Hand:", "Unit Price:\n"); //Header
    System.out.println("_______________________________________________________________________________\n");
    ItemNode current = head;
        if(current == null){
            System.out.println("The list is empty.");
        }else{
            while(current != null){
                current.display();
                current = current.getNext();
            }
        }
    }


public void displayOne()
{
    ItemNode current = findItem();
    if (current == null){
        System.out.println("\nInvalid input! Please try again:");
          }else{
        System.out.println("_______________________________________________________________________________\n");    
        System.out.println("                                 Inventory                                     ");
        System.out.println("_______________________________________________________________________________\n");
        System.out.printf("\n%-6s%-20s%-24s%-12s%-6s\n", "ID:", "Name:", "Description:","On Hand:", "Unit Price:\n"); //Header
        System.out.println("_______________________________________________________________________________\n");
            current.display();
        }
    }



}

ItemNode

import java.text.NumberFormat;

public class ItemNode
{
private int ID;
private String name;
private String Desc;
private int onHand;
private double unitPrice;
private ItemNode next;

public ItemNode(int pID)
{
    ID = pID;
}

public ItemNode(int pID, String pName, String pDesc, int pOnHand, double pUnitPrice) {
    ID = pID;
    name = pName;
    Desc = pDesc;
    onHand = pOnHand;
    unitPrice = pUnitPrice;
}

public void display()
{ 
    NumberFormat dollars = NumberFormat.getCurrencyInstance();
    System.out.printf("%-6s%-20s%-24s%-12s%-6s\n", ID, name, Desc, onHand, dollars.format(unitPrice));
}

// GETTERS AND SETTERS
public void setNext(ItemNode pNext)
{
    next = pNext;
}

public ItemNode getNext()
{
    return next;
}

public int getID()
{
    return ID;
}

public void setName(String pName)
{
    name = pName;
}

public String getName()
{
    return name;
}

public void setDesc(String pDesc)
{
    Desc = pDesc;
}

public String getDesc()
{
    return Desc;
}

    public void setOnHand(int pOnHand)
{
    onHand = pOnHand;
}

public int getOnHand()
{
    return onHand;
}
public void setUnitPrice(double pUnitPrice)
{
    unitPrice = pUnitPrice;
}

public double getUnitPrice()
{
    return unitPrice;
}

}

inventUserLL

import java.util.Scanner;

public class inventUserLL 
{

public static void main(String[] args) 
{

    InventoryLL myInvent = new InventoryLL();
    Scanner scannerObject = new Scanner(System.in);
    int Choice = 0;



        do{

        dispMenu();

        Choice = getChoice(scannerObject);

        proChoice(Choice, myInvent);

        }while (Choice !=0);


}

public static void dispMenu()
{
    System.out.println("\n|=============================================|");
    System.out.println("|                                             |");
    System.out.println("|******************Welcome********************|");
    System.out.println("|_____________________________________________|");
    System.out.println("|                                             |");
    System.out.println("|       Press [1] To Add An Item              |");
    System.out.println("|                                             |");
    System.out.println("|       Press [2] To Display One Item         |");
    System.out.println("|                                             |");
    System.out.println("|       Press [3] To Display All Items        |");
    System.out.println("|                                             |");
    System.out.println("|       Press [4] To Modify An Item           |");
    System.out.println("|                                             |");
    System.out.println("|       Press [0] To Exit                     |");
    System.out.println("|_____________________________________________|");
    System.out.println("|=============================================|");
    System.out.println("|         Please Make Selection Now...        |");
    System.out.println("|=============================================|");
    System.out.println("|_____________________________________________|\n");
    }

    public static int getChoice(Scanner scannerObject)
    {
        boolean x = false;
        int pChoice = 0;
            do{
             try{
                pChoice = scannerObject.nextInt();
                x = true;
            }catch (Exception e){
                scannerObject.next();
                System.out.println("\nInvalid command! Please try again:\n");
                }
            }while (x == false);
        return pChoice;
    }

    public static void proChoice(int Choice, InventoryLL myInvent)
    {

        switch(Choice){
            case 1: myInvent.addItem();
            break;
            case 2: myInvent.displayOne();
            break;
            case 3: myInvent.displayAll();
            break;
            case 4: myInvent.modify();
            break;
            case 0: System.out.println("\nHave a nice day!");
            break;
            }
    }
}

更新

public ItemNode findItem(){
    int inputID;
    boolean found = false;
    ItemNode current = head;
        try{
        System.out.print("\nGreetings, please enter the ID number for item:\n");
        inputID = scannerObject.nextInt();
        scannerObject.nextLine();
                if (head != null){
                    while ((current.getNext() != null) && (!found)) {
                        if (current.getID() == inputID){
                        found = true;
                        } 
                        if (!found){
                            current = current.getNext();
                            }   
                        }
                    if (!found){
                        current = null;
                        }   
                }                   
            }catch(Exception e)
            {
                System.out.println("\nERROR!");
            }
    return current;
}

假设根持有第一个节点值。

ItemNode root = ...;

public ItemNode findNode(int value){
   if(root !=null){
       ItemNode temp = root;
       while(temp!=null){
           if(temp.getID() == value) return temp;
           temp = temp.next;
       }
   }
   return null;
}

据我了解,您想删除方法中的 'break;' 并使该功能仍然有效?

你试过用'return current'替换'break;'吗?

public ItemNode findItem(){
    int inputID;
    boolean found = false;
    ItemNode current = null;
        try{
        System.out.print("\nGreetings, please enter the ID number for item:\n");
        inputID = scannerObject.nextInt();
        scannerObject.nextLine();
            for (current = head; !found; current = current.getNext()){
                if (current.getID() == inputID){                    
                    return current; // return the result when you find the node
                    }
                }       
            }catch(Exception e)
            {
                System.out.println("\nERROR!");
            }
    return current;
}

如果我没记错的话,"compound condition"如下:

if (head != null) {
    while ((current != null) && (!found)) {
        // check to see if you have the right value, set `found` if you do
        // otherwise, continue
        if (!found) { // do this otherwise you'll return the next value everytime
            current = current.getNext();
        }
    }
    if (!found) { // if you're at the end of the list and you didn't find the value
        // set current = to something you want to return if the value was not found
    }

}
return current;

您可以在不丢失语义的情况下删除中断。现在好像少了head的定义

您的指导员的意思:如果搜索的对象不在列表中,您的循环将导致 NullPointerException。因此,何时中断循环的条件还必须包含对现有下一个元素的检查,例如像这样:

for (current = head; !found && current.hasNext(); current = current.getNext()) {

而且你应该检查不要进入这个循环head == null