【问题标题】:Find the length of an arraylist when the arraylist is located in a different Class当arraylist位于不同的Class时,查找arraylist的长度
【发布时间】:2016-08-28 00:16:05
【问题描述】:

所以我试图找出数组列表的长度,但数组列表存储在不同的类中,我该如何解决这个问题。

import java.util.Scanner;
import java.util.*;
import java.util.ArrayList;

public class StarberksInterface
{


public static void main(String args[])
{

    Scanner console = new Scanner(System.in);
    store = new Store();
    String str, sName1, sName2, name;
    char c;
    int n=0;
    sName1 = "Callahan";
    sName2 = "Lambton";


    //This is the main menu that will be displayed first.
    System.out.println("       MAIN MENU FOR MANAGEMENT SYSTEM");
    System.out.println("===============================================");
    System.out.println("1. CHOOSE STORE");
    System.out.println("2. DISPLAY STORES");
    System.out.println("3. LOAD STORE VIA FILE");
    System.out.println("4. SAVE STORE TO FILE ");
    System.out.println("5. EXIT PROGRAM");
    System.out.println("===============================================");

    while(n!=5)// Exits the program when 4 is pressed
        {
            System.out.print("\n Please enter option 1-4 to continue...: ");
            n = Integer.parseInt(System.console().readLine());
            // Reads user input and takes them to selected code.
            if (n>5||n<1)
            {
                System.out.print("Invalid input, please try again...");
                continue;
            }
            if (n==1)// Takes to option 1 or sub menu
            {
                str="y";

                while(str.equals("y")||str.equals("Y"))
                {
                    System.out.println("Enter a store name [Callahan or Lambton] ");
                    name = console.next();
                    if (sName1.equals(name)|| sName2.equals(name))
                    {
                        StarberksInterface.subMenu();
                        continue;
                    }
                    else 
                    {
                        System.out.println("There is no store under this name. Please try again.");
                    }

                }

            }
            if (n==2)// Gathers products in stores and displays the number of products
            {
                System.out.println(" Store data is being displayed.");
                System.out.println("===============================");
                System.out.println("Store: Callahan");
                System.out.println("       Number of products: "+store.size());

            }
        }
}

所以上面的代码是我想要显示长度的地方。

此代码是填充数组列表的位置。

    public static Product product;
public static Store store;
// Where the user inputs the data for the item
public static void addItem ()
{
    Scanner console = new Scanner(System.in);
    product = new Product();// initiates the product and store to being empty.


    String desc, id, str="";
    double price = 0, sUpPrice = 0, unitCost = 0, inventoryCost = 0;
    int stock = 0, demand = 0;


        System.out.print("Please enter product description between 3 to 10 characters...: ");
        desc = console.next();
        desc = desc.toLowerCase();
        product.setName(desc);


        if ((desc.length() < 3 || desc.length() > 10))
        {
            System.out.println("\nThis Input is incorrect. Please make description between 3 to 10 characters.\n");
            System.out.println("Try again with different input. ");
            System.out.println("\n*****************************************\n");
            StarberksInterface.addItem();
        }

        System.out.print("Please enter price in $ : ");
        price = console.nextDouble();
        product.setPrice(price);

        if (price < 0)
        {
            System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
            System.out.println("Because of incorrect input, program will restart. ");
            System.out.println("\n*****************************************\n");
            StarberksInterface.addItem();
        }

        System.out.print("Please enter set up price. $ : ");
        sUpPrice = console.nextDouble();
        product.setsUpPrice(sUpPrice);

        if (sUpPrice < 0)
        {
            System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
            System.out.println("Because of incorrect input, program will restart. ");
            System.out.println("\n*****************************************\n");
            StarberksInterface.addItem();
        }

        System.out.print("Please enter unit- cost. $ : ");
        unitCost = console.nextDouble();
        product.setunitCost(unitCost);

        if (unitCost < 0)
        {
            System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
            System.out.println("Because of incorrect input, program will restart. ");
            System.out.println("\n*****************************************\n");
            StarberksInterface.addItem();
        }

        System.out.print("Please enter the inventory cost. $ : ");
        inventoryCost = console.nextDouble();
        product.setinvCost(inventoryCost);

        if (inventoryCost < 0)
        {
            System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
            System.out.println("Because of incorrect input, program will restart. ");
            System.out.println("\n*****************************************\n");
            StarberksInterface.addItem();
        }

        System.out.print("Please enter the amount in stock : ");
        stock = console.nextInt();
        product.setstock(stock);

        if (stock < 0)
        {
            System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
            System.out.println("Because of incorrect input, program will restart. ");
            System.out.println("\n*****************************************\n");
            StarberksInterface.addItem();
        }

        System.out.print("Please enter the demand of the product : ");
        demand = console.nextInt();
        product.setdRate(demand);

        if (demand < 0)
        {
            System.out.println("\nThis Input is incorrect. Please make sure attributes are positve numbers\n");
            System.out.println("Because of incorrect input, program will restart. ");
            System.out.println("\n*****************************************\n");
            StarberksInterface.addItem();
        }

        System.out.println("\n*****************************************\n");
        System.out.print(desc +" Product was added successfully ");
        System.out.println("\n*****************************************\n");
        // stores the item in the array


        //Checks to see if item is already in the list
        /*while (product != null)
        {
            if (product.equals(store.getProduct(desc)))
            {
                System.out.println(desc +" is already a product.");
                System.out.println("Input for data will restart");
                StarberksInterface.addItem();
            }
        }*/

        store.add(product);
    }

最后,下面的代码在一个名为 Store.java 的文件中,这是 arraylist 所在的位置。

import java.util.ArrayList;

public class Store{
// stores the product information in an array list
//allows for numerous products and each can be called in the Starberks Interface
public ArrayList <Product> ProductList = new ArrayList<Product> ();

public Store()
{

}

public void add(Product product)
{   
    // Adds the product and all details entered by user to the list.        
    ProductList.add(product);
}

public Product getProduct(String prodName) {
    //
    for (int i = 0; i < ProductList.size(); i++) {
            //searches through list of products to find a specific name entered in
            // from the Starberks Interface
        if (ProductList.get(i).getName().equals(prodName)) {
            return ProductList.get(i);
        }
    }
    return null;
 }

 }

【问题讨论】:

  • ArrayList.size() .... 你就是这样找到它的。添加到您的商店类...public int getNumberOfProducts() { return ProductList.size(); }
  • 你的Store类是不同的项目还是在同一个项目中?
  • 我猜您希望在您输入store.size() 的位置返回 ArrayList 的大小?要么将 store.size() 替换为 store.ProductList.size(),要么在 Store 类中编写一个返回“ProductList.size()”的方法。

标签: java file arraylist menu


【解决方案1】:

这不是另一个文件,而是另一个。要访问一个类的成员,您需要通过该类的对象来访问它。例如,在您的代码中,您可以使用new Store().ProductList 访问数组列表。虽然一开始这里是空的,但是当你往里面添加一些产品之后,这里就会有一些对象。

当您使用store.size() 时,我认为您需要在Store 类中声明一个方法size(),它将返回您的数组列表的大小。

顺便说一下,您的代码中存在一些一般性问题 1.类中的公共变量/对象 2. getProduct() 返回 null,隐藏了它的真正目的。

【讨论】:

  • 抱歉,代码的主要部分在名为 inv.java 的文件中,arraylist 在名为 store.java 的文件中
  • 这很好,Raznish,这就是我们分离类的方式。我们通常将每个公共类保存在它自己的文件中。我们仍然不称它们为文件,而是称它们为类,因为这就是它们在 Java 中的表示方式。我希望你对 Java 有一些基本的了解,而不是使用别人的代码。
【解决方案2】:

您需要在 Store 类中定义一个 getter 方法来访问列表的大小

/*your list reference has a size() method that you can call to get the size of list in store class and can access that via a getter */
public int getProductListSize(){

return ProductList.size();
}

此外,在您拥有存储类参考的任何其他类中,您都可以像访问它一样轻松访问它

store. getProductListSize();

【讨论】:

    猜你喜欢
    • 2016-07-21
    • 1970-01-01
    • 1970-01-01
    • 2012-02-04
    • 1970-01-01
    • 2014-06-14
    • 2018-10-03
    • 2017-04-28
    • 1970-01-01
    相关资源
    最近更新 更多