开发者

How to add an array to store items?

I am new to java and am writing a program for class that I have to modify so that it can handle multiple items and I need to use an array to store the items. This is what I have so far.

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.n开发者_C百科extLine();

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

The question is how do I create an array that can hold both string and int elements? I need the array to hold the DVD name, id, unit price, units in stock, and total inventory value.


Using a java.util.Collection would make more sense, but if you HAVE to use an array for your homework:

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


Look Collection and List as start point.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜