如何添加数组来存储项目?

时间:2011-08-31 16:12:50

标签: java

我是java新手,我正在为类编写一个程序,我必须修改它以便它可以处理多个项目,我需要使用数组来存储项目。这是我到目前为止所做的。

public class ProductDVD
    {
    private String productName;
    private int productID;
    private long unitsInStock;
    private float unitPrice;

public void setName( String productName )
    {
    this.productName = productName;
    }

public void setProductID( int productID )
    {
    this.productID = productID;
    }

public void setUnitsInStock( long unitsInStock )
    {
    this.unitsInStock = unitsInStock;
    }

public void setUnitPrice( float unitPrice )
    {
    this.unitPrice = unitPrice;
    }

    public String getName()
    {
    return productName;
    }

    public int getProductID()
    {
    return productID;
    }

    public long getUnitsInStock()
    {
    return unitsInStock;
    }

    public float getUnitPrice()
    {
    return unitPrice;
    }

    public float getInventoryValue()
    {
    return( unitsInStock * unitPrice );
    }
    }


import java.util.Scanner;

    public class DVDinventory
    {
    public static void main( String args [] )
    {
    Scanner input = new Scanner( System.in );

    ProductDVD dvd = new ProductDVD();

    System.out.print( "Enter a DVD Title: " );
    dvd.setName( input.nextLine() );

    System.out.print( "Enter the Product ID: " );
    dvd.setProductID( input.nextInt()); 

    System.out.print( "Enter the Product's Unit Price: " );
    dvd.setUnitPrice( input.nextFloat() );

    System.out.print( "Enter the Number of Units in Stock: " );
    dvd.setUnitsInStock( input.nextLong() );

    input.nextLine();

    System.out.println( "Name:          " + dvd.getName() );
    System.out.println( "ID:            " + dvd.getProductID() );
    System.out.println( "Unit Price:        " + dvd.getUnitPrice() );
    System.out.println( "Units in Stock:        " + dvd.getUnitsInStock() );
    System.out.println( "Inventory Value:   " + dvd.getInventoryValue() );
    }
    }

问题是如何创建一个可以同时包含string和int元素的数组?我需要数组来保存DVD名称,ID,单价,库存单位和总库存值。

2 个答案:

答案 0 :(得分:2)

使用java.util.Collection会更有意义,但是如果你必须使用数组作为你的作业:

private static int INVENTORY_SIZE = 42; //that's what you mean by total inventory value, right?

ProductDVD[] dvds = new ProductDVD[INVENTORY_SIZE];

Scanner input = new Scanner( System.in );

for (int i = 0; i < INVENTORY_SIZE; i++) {
    dvds[i] = new ProductDVD();  
    //your code to read in data here...
}

答案 1 :(得分:1)

CollectionList为起点。