简体   繁体   English

如何搜索Java链接列表

[英]How do I search through a Java Linked List

I am working on my last assignment for my intro Java class. 我正在为Java入门课程做最后的作业。 We are doing a Linked List (we built ourselves) Inventory program. 我们正在做一个链表(我们自己建立)清单程序。 I am having trouble with my findItem method. 我的findItem方法遇到麻烦。 How would I search through my Linked List by Item number?? 如何按商品编号搜索链接列表? The way I am doing it works, but I need to get rid of the break. 我的工作方式可行,但我需要摆脱休息。 My instructor said I "need to set a compound condition, the !found you have and the not null." 我的讲师说我“需要设置一个复合条件,即找到您拥有的条件,而不是null”。 I have tried several different variations and cannot get it. 我尝试了几种不同的变体,但无法获得。 Please, any help, suggestions, or examples would be greatly appreciated, its finals week and everything is due tomorrow. 请帮助,任何帮助,建议或示例,我们将在决赛周和明天应有尽有。 My main issue is in findItem() in InventoryLL class, but I posted the whole code for context. 我的主要问题是InventoryLL类中的findItem(),但我发布了整个上下文代码。

InventoryLL 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 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 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;
            }
    }
}

UPDATE UPDATE

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;
}

If i'm not wrong here, a "compound condition" is as follows: 如果我在这里没有记错,则“复合条件”如下:

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;

Assuming root holds the first Node value. 假设root拥有第一个Node值。

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;
}

May I understand that you want to remove the 'break;' 我是否可以理解您要删除该“中断”? in your method and get the function still work? 在您的方法中并获得功能仍然有效?

Did u try that replace 'break;' 您是否尝试过用“ break”代替? with 'return current'? 与“返回电流”?

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;
}

You can remove the break without loss of semantics. 您可以删除中断而不会失去语义。 Now the definition of head seems to be missing. 现在头的定义似乎丢失了。

What your instructor means: Your loop would cause a NullPointerException if the searched object is not in the list. 指导者的含义:如果搜索到的对象不在列表中,则循环将导致NullPointerException So the condition when to break the loop must also contain a check on an existing next element, eg like this: 因此,中断循环的条件还必须包含对现有下一个元素的检查,例如:

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

And you should check not to enter this loop with head == null . 并且您应该检查不要使用head == null进入此循环。

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

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