有 Java 编程相关的问题?

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

java如何从用户输入中删除2d数组中的行

如何从用户输入中删除二维数组中的行。我想用一个复制数组来覆盖原始的2d数组,但我似乎找不到语法来做这件事。另外,我希望复制数组覆盖原始数组,这样其他方法就不会受到影响

static String data[][] = new String[3][100];
int max = 0;

static void start() {
    p2("---INVENTORY OPTIONS---");
    p2("1. VIEW Inventory");
    p2("2. ADD Product(Name, Price, Quantity)");
    p2("3. UPDATE Product(Name, Price, Quantity)");
    p2("4. DELETE Product(Name, Price, Quantity)");
    p1("Enter inventory option: ");
    String q2a = stringscan();

    if (q2a.equals("1")) {
        invview();
    } else if (q2a.equals("2")) {
        invadd(q2a);
    } else if (q2a.equals("3")) {
        invupdate(q2a);
    } else if (q2a.equals("4")) {
        invdelete(q2a);
    }
}

static void invupdate(String q2a) {
    if (q2a.equals("3")) {
        p1("Input Product name to update: ");
        String edit = stringscan();
        for (int i = 1; i <= data.length; i++) {
            if (data[0][i].contains(edit)) {
                System.out.print("Edit or Retain Product Name [" + i + "]: ");
                String qname = stringscan();
                data[0][i] = qname;

                System.out.print("Edit or Retain Product Price [" + i + "]: ");
                String qprice = stringscan();
                data[1][i] = qprice;

                System.out.print("Edit or Retain Product Quantity [" + i + "]: ");
                String qqty = stringscan();
                data[2][i] = qqty;
            }
        }
        invview();
        start();
    }
}

int[][] copy = new int[data.length - 1][data.length - 1];
static void invdelete(String q2a) {
    if (q2a.equals("4")) {
        p1("Input Product name to delete: ");
        String edit = stringscan();
        for (int i = 1, j = 1; i <= data.length; i++) {
            if (!data[0][i].contains(edit)) {
                ///how to remove row from 2d array
            }
        }
        invview();
        start();
    }
}

共 (1) 个答案

  1. # 1 楼答案

    要使此任务更简单、更灵活,您可能需要做的第一件事是创建一个产品类,例如:

    public class Products {
        
        // Hold instances of Products
        public static java.util.List<Products> products = new java.util.ArrayList<>();
        
        // Instance (class member) variables
        private String productName;
        private double productPrice;
        private int    productQuantity;
    
        // Constructor #1:
        public Products() {   
            products.add((this));
        }
    
        // Constructor #2:
        public Products(String name, double price, int quantity) {
            this.productName = name;
            this.productPrice = price;
            this.productQuantity = quantity;
            products.add((this));
        }
    
        // Getters and Setters
        public String getProductName() {
            return productName;
        }
    
        public void setProductName(String productName) {
            this.productName = productName;
        }
    
        public double getProductPrice() {
            return productPrice;
        }
    
        public void setProductPrice(double productPrice) {
            this.productPrice = productPrice;
        }
    
        public int getProductQuantity() {
            return productQuantity;
        }
    
        public void setProductQuantity(int productQuantity) {
            this.productQuantity = productQuantity;
        }
    
        public static java.util.List<Products> getProducts() {
            return products;
        }
    
        // Public class Utility Methods
        @Override
        public String toString() {
            return new StringBuilder(productName).append(", ").append(String.valueOf(productPrice))
                                     .append(", ").append(String.valueOf(productQuantity)).toString();
        }
        
        public static String toStringTable() {
            StringBuilder productsTable = new StringBuilder("         - Products Table  -");
            productsTable.append(System.lineSeparator());
            String header = String.format(java.util.Locale.US, "%-20s %-10s %-8s %n", "Product Name", "Price", "Quantity");
            productsTable.append(header);
            String underline = String.join("", java.util.Collections.nCopies(header.length()-3, "="));
            productsTable.append(underline).append(System.lineSeparator());
            for (Products p : products) {
                String tableRow = String.format(java.util.Locale.US, "%-20s %-10.2f %-8d %n", 
                        p.getProductName(), p.getProductPrice(), p.getProductQuantity());
                productsTable.append(tableRow);
            }
            productsTable.append(underline);
            return productsTable.toString();
        }
        
        public static boolean loadProducts(String filePath) {
            try (java.util.Scanner reader = new java.util.Scanner(new java.io.File(filePath))) {
                Products.products.clear();
                while (reader.hasNextLine()) {
                    String line = reader.nextLine().trim();
                    if (line.isEmpty() || line.startsWith("#")) {
                        continue;
                    }
                    String[] lineParts = line.split("\\s*,\\s*");
                    String name = lineParts[0];
                    double price = Double.valueOf(lineParts[1].isEmpty() ? "0.0" : lineParts[1]);
                    int qty = Integer.valueOf(lineParts[2].isEmpty() ? "0" : lineParts[2]);
                    Products tmp = new Products(name, price, qty);
                }
                return true;
            }
            catch (java.io.FileNotFoundException ex) {
                java.util.logging.Logger.getLogger("Products.loadProducts() Method Error!")
                        .log(java.util.logging.Level.SEVERE, null, ex);
            }
            return false;
        }
        
        public static boolean saveProducts(String filePath) {
            java.io.File file = new java.io.File(filePath);
            try (java.io.FileWriter fw = new java.io.FileWriter(file)) {
                // creates the file
                file.createNewFile();
                fw.write("#  - Products File  -" + System.lineSeparator());
                for (Products p : Products.products) {
                    fw.write(p.toString() + System.lineSeparator());
                    fw.flush();
                }
                return true;
            }
            catch (java.io.IOException ex) {
                java.util.logging.Logger.getLogger("Products.saveProducts() Method Error!")
                                 .log(java.util.logging.Level.SEVERE, null, ex);
            }
            return false;
        }
    }
    

    当然,这意味着需要对代码的主要操作体进行更改,以利用产品的实例包含在List Inteface中的事实,从而更容易从实际创建的集合中添加和删除。使用收集机制(如列表)可以动态增大或减小其大小,而使用数组则需要处理固定大小的对象,并且几乎需要跳转(也就是说)来修改添加到或从中删除

    利用上面提供的类和下面提供的代码,您将得到一个基本的可运行的产品清单控制台应用程序。当代码运行时,您可能会注意到的第一件事是主菜单稍微大一点。现在有七(7)个菜单项,而不是四(4)个菜单项。添加了加载库存保存库存退出等菜单项

    菜单任务(退出除外)完成后,将始终显示主菜单。这当然允许应用程序连续运行,而无需重新运行。可以根据需要在库存中添加、更改或删除产品。库存中的产品表也可以随时查看。添加的产品也可以保存到本地文件系统中的产品文件中。该文件名目前硬编码为“Products.txt”,应根据用户的需要进行更改。像这样的硬编码从来都不是一个好主意,但在这里只是为了简单演示

    在删除注释之前,请阅读代码中的所有注释:

    public class Inventory {
        
        // Class Field variables
        private final java.util.Scanner USERINPUT = new java.util.Scanner(System.in);
        private final String NL = System.lineSeparator();
        
        public static void main(String[] args) {
            new Inventory().start();
        }
        
        private void start() {
            //Main Menu...
            String q2a = "";
            /* WHILE loops are used for all prompts so that validity 
               checks can be done and the User has the oportunity to
               make a correct entry.                             */
            while (!q2a.equals("7")) {
                p2(" -INVENTORY OPTIONS -");
                p2("1. LOAD Inventory");
                p2("2. VIEW Inventory");
                p2("3. ADD Product(Name, Price, Quantity)");
                p2("4. UPDATE Product(Name, Price, Quantity)");
                p2("5. DELETE Product(Name, Price, Quantity)");
                p2("6. SAVE Inventory");
                p2("7. QUIT");
                p1("Enter inventory option:  > ");
                q2a = stringscan();
                // Validate User Input...
                // Only a single digit from 1 to 7 is acceptable.
                if (!q2a.matches("[1-7]")) {
                    p3("Invalid menu choice! Try again...");
                    p2("");  // Add a blank line to console window.
                    continue;   // Redisplay main menu
                }
                p2("");
    
                // Process Menu Selection...
                switch (q2a) {
                    // Load Inventory
                    case "1":
                        invload("Products.txt");
                        p2("");
                        break;
                    // View Products Table
                    case "2":
                        invview();
                        p4();
                        break;
                    // Add to Products
                    case "3":
                        invadd();
                        break;
                    // Change a Product item
                    case "4":
                        invupdate();
                        break;
                    // Delete a Product Item
                    case "5":
                        invdelete();
                        break;
                    // Save Products List to file
                    case "6":
                        invsave("Products.txt");
                        p2("");
                        break;
                    // Quit the application.
                    case "7":
                        p2("Quiting...Bye-Bye");
                        System.exit(0);
                }
            }
        }
    
        // User Input request.
        private String stringscan() {
            return USERINPUT.nextLine();
        }
        
        // Console 'print'
        private void p1(String text) {
            System.out.print(text);
        }
    
        // Console 'println'
        private void p2(String text) {
            System.out.println(text);
        }
    
        // Console 'err.println'
        private void p3(String text) {
            System.err.println(text);
        }
    
        // Console 'Enter To Continue' prompt
        private void p4() {
            p2("<< Press ENTER to continue >>");
            stringscan();
        }
    
        // Display Products Table to Console.
        private void invview() {
            // See if the instances List actually contains anything:
            if (Products.products.isEmpty()) {
                p3("There are no Products yet to view!");
                p2("");
                return;
            }
    
            p2(Products.toStringTable());
        }
    
        private void invadd() {
            String name = "";
            // Product Name Prompt...
            while (name.isEmpty()) {
                p1("What is the product Name you want to add?  > ");
                name = stringscan().trim();
            }
            
            // Is the Product already in the List?
            for (Products p : Products.products) {
                String pName = p.getProductName();
                if (pName.equalsIgnoreCase(name)) {
                    // Yes it is so inform User and get out of here.
                    p3("The product named '" + pName + "' is already contained" + NL
                       + "within the Products Inventory List!" + NL);
                    return;
                }
            }
    
            // Product Price Prompt...
            String priceString = "";
            while (priceString.isEmpty()) {
                p1("What is the product price?  > ");
                priceString = stringscan().trim();
                // Validate User Input...
                /* The Regular Expression used in the String#matches() method
                   validates the fact that a string representation of a signed 
                   or unsigned numerical Integer or floating point value is
                   indeed supplied. If not the User is prompted again.      */
                if (!priceString.matches("-?\\d+(\\.\\d+)?")) {
                    p3("Invalid price supplied! Try again...");
                    p2("");
                    priceString = "";
                }
            }
            // Convert string numerical value to double data type.
            double price = Double.valueOf(priceString);
    
            // Product Quantity Prompt...
            String quantityString = "";
            while (quantityString.isEmpty()) {
                p1("What is the product quantity?  > ");
                quantityString = stringscan().trim();
                // Validate User Input...
                /* The Regular Expression used in the String#matches() method
                   validates the fact that a string representation of a signed 
                   or unsigned numerical Integer value is indeed supplied. If 
                   not the User is prompted again.      */
                if (!quantityString.matches("-?\\d+")) {
                    p3("Invalid quantity supplied! Try again...");
                    p2("");
                    priceString = "";
                }
            }
            // Convert string numerical value to int data type.
            int quantity = Integer.valueOf(quantityString);
    
            /* Create an instance of this product which ultimately 
               gets stored within the Products List (products). */
            Products products = new Products(name, price, quantity);
            // Inform User of successful product addition.
            p2("Product was added to inventory!");
            p2("");
        }
    
        private void invupdate() {
            // Are the actually products in inventory to update?
            if (Products.products.isEmpty()) {
                // No...Inform User and get out of here.
                p3("There are no Products yet to update!");
                p2("");
                return;
            }
            p2(" - Product Update  -");
            String pName = "";
            while (pName.isEmpty()) {
                p1("Enter the Product name to update (q to go-back):  > ");
                pName = stringscan();
                if (pName.equalsIgnoreCase("q")) {
                    p2("");
                    return;
                }
                boolean foundProduct = false;
                for (Products p : Products.products) {
                    String productName = p.getProductName();
                    double productPrice = p.getProductPrice();
                    int productQuantity = p.getProductQuantity();
                    // Find the desired product...
                    if (productName.equalsIgnoreCase(pName)) {
                        // Product Found...
                        // Change Product Name?
                        foundProduct = true;
                        p2("Enter new Product Name for '" + productName + "' or");
                        p1("just hit ENTER to keep it:  > ");
                        pName = stringscan();
                        if (pName.isEmpty()) {
                            pName = productName;
                        }
    
                        // Change Product Price?
                        String pPrice = "";
                        while (pPrice.isEmpty()) {
                            p2("");
                            p2("Enter a new Product Price for '" + pName + "' or");
                            p1("just hit ENTER to keep the old price of [$"
                                    + productPrice + "]:  > ");
                            pPrice = stringscan();
                            if (pPrice.isEmpty()) {
                                pPrice = String.valueOf(productPrice);
                            }
                            if (!pPrice.matches("-?\\d+(\\.\\d+)?")) {
                                p3("Invalid price (" + pPrice + ") supplied! Try again...");
                                p3("");
                                pPrice = "";
                            }
                        }
                        double price = Double.valueOf(pPrice);
    
                        // Change Product Quantity?
                        String pQty = "";
                        while (pQty.isEmpty()) {
                            p2("");
                            p2("Enter a new Product Quantity for '" + pName + "' or");
                            p1("just hit ENTER to keep the old Quantity of ["
                                    + productQuantity + "]:  > ");
                            pQty = stringscan();
                            if (pQty.isEmpty()) {
                                pQty = String.valueOf(productQuantity);
                            }
                            else if (!pQty.matches("-?\\d+")) {
                                p3("Invalid price (" + pQty + ") supplied! Try again...");
                                p3("");
                                pQty = "";
                            }
                        }
                        int quantity = Integer.valueOf(pQty);
                        p.setProductName(pName);
                        p.setProductPrice(price);
                        p.setProductQuantity(quantity);
                        p2("Product was Updated!");
                        break;
                    }
                }
                if (!foundProduct) {
                    p3("Could not locate the product named: " + pName + "! Try again...");
                    p2("");
                    pName = "";
                }
    
            }
    
            // View Products Table to show changes (if any):
            p2("");
            invview();
            p4();
        }
    
        private void invdelete() {
            // Are the actually products in inventory to delete?
            if (Products.products.isEmpty()) {
                // No...Inform User and get out of here.
                p3("There are no Products yet to delete!");
                p2("");
                return;
            }
            p2(" - Product Delete  -");
            String pName = "";
            while (pName.isEmpty()) {
                // Allow the option to cancel process by entering 'q'.
                p1("Enter the Product name to delete (q to go-back):  > ");
                pName = stringscan();
                // Was 'q' supplied to cancel process?
                if (pName.equalsIgnoreCase("q")) {
                    // Yes... get out of here.
                    p2("");
                    return;
                }
    
                // Find the desired Product (not letter case sensitive)
                boolean foundProduct = false;
                String productName = "";
                for (int i = 0; i < Products.products.size(); i++) {
                    productName = Products.products.get(i).getProductName();
                    if (productName.equalsIgnoreCase(pName)) {
                        foundProduct = true;
                        // Remove the Product from the Porducts List (products).
                        Products.products.remove(i);
                        break;
                    }
                }
                // Inform the User of the outcome.
                if (foundProduct) {
                    p2("The Product (" + productName + ") was deleted!");
                }
                else {
                    p3("Could not locate the product named: " + pName + "! Try again...");
                    p2("");
                    pName = "";
                }
            }
    
            // View Products Table to show deletions (if any):
            p2("");
            invview();
            p4();
        }
    
        private void invload(String filePath) {
            // See the the supplied Products file exists....
            if (!new java.io.File(filePath).exists()) {
                // No it doesn't so inform User and get out of here.
                p3("There is no Products file yet to load!");
                p3("");
                return;
            }
            // Load in all Products from the supplied products file.
            if (Products.loadProducts(filePath)) {
                p2("Products file loaded!");
                if (Products.products.isEmpty()) {
                    p2("There were no products found within the Products file!");
                }
            }
        }
    
        private void invsave(String filePath) {
            /* See if there are actual products within the 
               Products List (products) to be saved...  */
            if (Products.products.isEmpty()) {
                // No there isn't so inform User and get out of here.
                p3("There are no Products yet to save!");
                p2("");
                return;
            }
            
            // Save all the products to the local file system.
            if (Products.saveProducts(filePath)) {
                p2("Products List Successfully Saved!");
            }
        }
    }