有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

链表在Java中如何通过LinkedList搜索具有特定变量的对象?

我有一个问题,我可以用对象填充LinkedList,稍后我可以在我设计的这个商店系统中操作这些对象。问题是,当我用多个对象填充列表,然后在列表中搜索该对象时;我的程序会告诉我,我正在寻找的对象不存在,即使我可以列出列表的内容,它也会显示出来

任何帮助都将不胜感激

import java.io.*;
import java.util.*;

public class Sales extends addVideoGame implements java.io.Serializable{

private static LinkedList<VideoGames> sellGame = new LinkedList<>();
private static String searchTerm;
private static int searchQ;

public static void sellItem(){
    sellGame = games;
    int listLength = sellGame.size();
    searchTerm = IBIO.inputString("What item would you like to sell: ");
    for(VideoGames v : sellGame){
    if(v.getTitle().contains(searchTerm)){
        IBIO.output("Item found: " + searchTerm);
        searchQ = v.getQuantity();
        IBIO.output("Available Quantity: " + searchQ);
        int sellQ = IBIO.inputInt("How much of this item would you like to sell: ");
        if(sellQ > searchQ){
            IBIO.output("The amount you have specified is greater than the \ncurrent stock.");
            sellItem();
        } else {
            searchQ = searchQ - sellQ;
            v.setQuantity(searchQ);
            double sellP;
            sellP = sellQ * v.getPrice();
            IBIO.output("£"+sellP);
            String confirm = IBIO.input("This is the price you are selling these items for. Type 'Yes' to complete the order or 'No' to reject it. ");
            if(confirm.equalsIgnoreCase("Yes")){
                IBIO.output("Order complete!");
                try{
                    int receiptCount = 0;
                    PrintWriter receipt = new PrintWriter("C:\\Users\\Yemi\\Desktop\\TheStore\\receipt"+ receiptCount +".txt");
                    receipt.println("Item sold: " + v.getTitle());
                    receipt.println("Quantity sold: " + sellQ);
                    receipt.close();
                    receiptCount = receiptCount + 1;
                    IBIO.output("Receipt saved to: C:\\Users\\Yemi\\Desktop\\TheStore");
                } catch(IOException io){
                    io.printStackTrace();
                }
                IBIO.output("Thank you for buying from Gamers Avenue UK!");
            } else if(confirm.equalsIgnoreCase("No") && TheStore.privilege){
                AccessMenus.adminMenu();
            } else {
                AccessMenus.userMenu();
            }
            if(TheStore.privilege){
                AccessMenus.adminMenu();
            } else {
                AccessMenus.userMenu();
            }
        }
    } else {
        IBIO.output("The item you are looking for does not exist.");
        sellItem();
    }
    }
}
}

以下是用于在任何人需要时导航程序的类:

public class TheStore {

static String password; //Variable created to hold and check the value of password against the correct value.
public static boolean privilege = false; //Variable created to distinguish the difference between a normal user and a user with administrator privileges.

public static void main(String[] args) {
    IBIO.output("Welcome to Gamers Avenue UK!");
    IBIO.output("Please make sure that you enter the correct password for your given privileges.");
    password = IBIO.inputString("Enter password: ");
    if(password.equalsIgnoreCase("admin")){ //Checks the entered value against the correct value.
        privilege = true; //Sets global boolean value to true, so that admin access is granted.
        IBIO.output(" ");
        AccessMenus.adminMenu();//If password is correct, loads admin menu.
    } else if(password.equalsIgnoreCase("user")){
        privilege = false; //Keeps admin access off, so that unauthorised changes cannot be made.
        IBIO.output(" ");
        AccessMenus.userMenu();//If correct, loads user menu.
    } else {
        IBIO.output("The password is incorrect. Exiting program."); 
        System.exit(1); //If an incorrect password is entered, the program will close.
    } //close else
}//close main
}//close class TheStore

访问菜单:

public class AccessMenus{

    public static int choice;//Variable which will hold the value, which corresponds to an action depending on what value is entered.

    public AccessMenus(){ //Null argument constructor, to set values to 0.
        AccessMenus.choice = 0;
    }

    public AccessMenus(int c){ //Single argument constructor.
        AccessMenus.choice = c;
    }

    public static void userMenu(){
        IBIO.output("1: Sell a product.");
        IBIO.output("2: Register a customer in the Loyalty programme.");
        IBIO.output("3: Stock check.");
        IBIO.output("4: Log out.");
        IBIO.output(" ");
        IBIO.output("Please make your choice: ");
        choice = IBIO.inputInt();
        if(choice == 1){
            Sales.sellItem();
        } else if(choice == 2){
            CustomerRandom.customerMenu();
        } else if(choice == 3){
            StockCheck.checkStock();
        } else if(choice == 4){
            IBIO.output("Logging out.");
            System.exit(1);
        } else {
            IBIO.output("Invalid choice. Returning to menu.");
            userMenu(); //If the value entered does not correspond to any action, the program will treat it as invalid and return to the menu.
        }//close else
    }//close userMenu

    public static void adminMenu(){
        IBIO.output("1: Sell a product.");
        IBIO.output("2: Go the Videogame management menu.");
        IBIO.output("3: Stock check.");
        IBIO.output("4: Register a customer in the Loyalty programme.");
        IBIO.output("5: Log out.");
        IBIO.output(" ");
        IBIO.output("Please make your choice: ");
        choice = IBIO.inputInt();
        if(choice == 1){
            Sales.sellItem();
        } else if(choice == 2){
            addVideoGame.vgMenu();
        }else if(choice == 3){
            StockCheck.checkStock();
        } else if(choice == 4){
            CustomerRandom.customerMenu();
        } else if(choice == 5){
            IBIO.output("Logging out.");
            System.exit(1);
        } else {
            IBIO.output("Invalid input. Returning to menu.");
            adminMenu();
        } //end else
    }//close AdminMenu
}//close AccessMenus

此类是必需的,因为它允许您填充列表:

import java.util.*;
import java.io.*;

public class addVideoGame extends VideoGames implements java.io.Serializable{

public static VideoGames game = new VideoGames();
public static VideoGames eGame = new VideoGames();
public static LinkedList <VideoGames> games = new LinkedList<>();
public static LinkedList <VideoGames> loadList = new LinkedList<>();
private static int vgChoice = 0;
public static int vgCount = 0;
public static int vgAmount = 0;

public static void vgMenu(){
    IBIO.output("WARNING: USING OPTION 4 TO LOAD IN A LOCAL FILE WILL ERASE EVERYTHING CONTAINED IN THE CURRENT LIST. \nSave everything in the current list using option 3 before loading in data.");
    IBIO.output("1: Add a new videogame to the list.");
    IBIO.output("2: View the contents of the list.");
    IBIO.output("3: Save the contents of the list to the local area.");
    IBIO.output("4: Load in data from a local file.");
    IBIO.output("5: Return to the main menu.");
    vgChoice = IBIO.inputInt("Make your choice: ");

    if(vgChoice == 1){
        vgAmount = IBIO.inputInt("How many games would you like to add to the database?: ");
        for(int x = 0; x < vgAmount; x = x + 1){
        VideoGames vg = new VideoGames(); 
        vg.setTitle(IBIO.inputString("Enter the title of the game: "));
        vg.setPublisher(IBIO.inputString("Enter the publisher of the game: "));
        vg.setDeveloper(IBIO.inputString("Enter the developer of the game: "));
        vg.setAgeRating(IBIO.inputInt("Enter the age rating of the game: "));
        vg.setGenre(IBIO.inputString("Enter the genre of the game: "));
        vg.setQuantity(IBIO.inputInt("Enter the available quantity of the game: "));
        vg.setPrice(IBIO.inputDouble("Enter the recommended retail price: "));
        game = vg;
        games.add(vg);
        IBIO.output(" ");
        }
        vgMenu();
    } else if(vgChoice == 2){
        IBIO.output("Current amount of games in the list: " + games.size());
            Iterator itr = games.iterator();
            while(itr.hasNext()){
                Object g = itr.next();
                IBIO.output(g + " ");
            }
            //System.out.println(Arrays.toString(games.toArray()));
        vgMenu();
    } else if(vgChoice == 3){
        try{
            ListIterator output = games.listIterator();
            while(output.hasNext()){
            Object o = output.next();
            FileOutputStream fileOut = new FileOutputStream("C:\\Users\\Yemi\\Desktop\\TheStore\\games.ser");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(game);
            out.close();
            fileOut.close();
            IBIO.output("Data saved to C:\\Users\\Yemi\\Desktop\\TheStore\\games.ser");
            }
        } catch(IOException io){
                io.printStackTrace();
            }
        vgMenu();
    } else if(vgChoice == 4){
        eGame = null;
        try{
            ListIterator input = games.listIterator();
            while(input.hasNext()){
            Object i = input.next();
            FileInputStream fileIn = new FileInputStream("C:\\Users\\Yemi\\Desktop\\TheStore\\games.ser");
            ObjectInputStream in =  new ObjectInputStream(fileIn);
            eGame = (VideoGames) in.readObject();
            in.close();
            fileIn.close();
            games.clear();
            games.add(eGame);
            IBIO.output("Item added to list from local file.");
            }
        } catch (IOException i){
            i.printStackTrace();
            return;
        } catch(ClassNotFoundException c){
            IBIO.output("VideoGames class not found");
            c.printStackTrace();;
            return;
        }
        vgMenu();
    } else if(vgChoice == 5){
        IBIO.output("Returning to main menu: ");
        AccessMenus.adminMenu();
    } 
}     
}

再次感谢您的帮助


共 (1) 个答案

  1. # 1 楼答案

    我猜这个错误是由else内循环内的sellItem()块引起的。 试试这个(尽管我仍然认为你应该在最终的if中删除对sellItem()的调用):

    import java.io.*;
    import java.util.*;
    
    public class Sales extends addVideoGame implements java.io.Serializable{
    
        private static LinkedList<VideoGames> sellGame = new LinkedList<>();
        private static String searchTerm;
        private static int searchQ;
    
        public static void sellItem(){
            sellGame = games;
            int listLength = sellGame.size();
            searchTerm = IBIO.inputString("What item would you like to sell: ");
            boolean foundItem = false;
            for(VideoGames v : sellGame){
                if(v.getTitle().contains(searchTerm)){
                    foundItem = true;
                    IBIO.output("Item found: " + searchTerm);
                    searchQ = v.getQuantity();
                    IBIO.output("Available Quantity: " + searchQ);
                    int sellQ = IBIO.inputInt("How much of this item would you like to sell: ");
                    if(sellQ > searchQ){
                        IBIO.output("The amount you have specified is greater than the \ncurrent stock.");
                        sellItem();
                    } else {
                        searchQ = searchQ - sellQ;
                        v.setQuantity(searchQ);
                        double sellP;
                        sellP = sellQ * v.getPrice();
                        IBIO.output("£"+sellP);
                        String confirm = IBIO.input("This is the price you are selling these items for. Type 'Yes' to complete the order or 'No' to reject it. ");
                        if(confirm.equalsIgnoreCase("Yes")){
                            IBIO.output("Order complete!");
                            try{
                                int receiptCount = 0;
                                PrintWriter receipt = new PrintWriter("C:\\Users\\Yemi\\Desktop\\TheStore\\receipt"+ receiptCount +".txt");
                                receipt.println("Item sold: " + v.getTitle());
                                receipt.println("Quantity sold: " + sellQ);
                                receipt.close();
                                receiptCount = receiptCount + 1;
                                IBIO.output("Receipt saved to: C:\\Users\\Yemi\\Desktop\\TheStore");
                            } catch(IOException io){
                                io.printStackTrace();
                            }
                            IBIO.output("Thank you for buying from Gamers Avenue UK!");
                        } else if(confirm.equalsIgnoreCase("No") && TheStore.privilege){
                            AccessMenus.adminMenu();
                        } else {
                            AccessMenus.userMenu();
                        }
                        if(TheStore.privilege){
                            AccessMenus.adminMenu();
                        } else {
                            AccessMenus.userMenu();
                        }
                    }
                    break;
                }
            }
            if(!foundItem) {
                IBIO.output("The item you are looking for does not exist.");
                sellItem();
            }
        }
    }
    

    虽然这可能有效,但我通常建议将searchTerm转换为函数的参数searchQ转换为函数的返回值。这样做会增加并发进程之间的隔离,并澄清正确执行函数需要哪些参数