Add an element to an array of object

1.1k Views Asked by At

I have a class called receipt and one of the attributes is an array item[] items; and I have a method addItem (string name , int quantity , double price). My question is how can I add these parameters to the array items[]? And how do I check if the quantity is more than 0?
Whats the code? Is my question clear?
Hers is my code:

public boolean addItem(String name, int quantity,double price){
if(quantity <= 0){
    System.out.println("Item wasnt added");
    return false;}
    else{
        item [nItem++];//here is the problem
    }
    }
5

There are 5 best solutions below

1
On

You could use an item object as parameter rather than transmitting each individual properties.
If you use an array, you should have a variable which stores the index of the last element added in the array.

Item could have a constructor and required getters :

public class Item{

  private String name;
  private int quantity;
  private double price;

 public Item(String name, int quantity, double price){
    this.name=name;
    this.quantity=quantity;
    this.price=price;
 }

  // required getters
}

public class Receipt{
   ...
   private int lastIndexUsed; // init to zero here
   ...
   private Item[] items = ...
   ...
    public boolean addItem(Item item){
      if(item.getQuantity() <= 0){
        System.out.println("Item wasnt added");
        return false;
      }
      else{
            items[lastIndexUsed++] = item;
        }
     }
}

How to use :

Receipt receipt = new Receipt();
receipt.addItem(new Item("itemOne", 10, 50));
receipt.addItem(new Item("itemTwo", 20, 80));
0
On

I can't find an answer that directly answers your question, so here.
I would use an ArrayList<Item> because it has the .add() method that you can call. You can later simply convert it to an array, if you need to, with .ToArray() (or something like that):

...
import java.util.ArrayList;
...

ArrayList<Item> items = new ArrayList<>();
...

public boolean addItem(String name, int quantity, double price){
    if(quantity <= 0) {
        System.out.println("Item wasnt added");
        return false;  
    }
    else {
        //System.out.println("Item was added"); //if you want
        items.add(new Item(name, quantity, price)); //Create new Item with your parameters...  
        return true;
    }
}

Not sure if Java syntax is correct, your IDE will help you.

0
On

Or you could use an ArrayList

public class Item{

  private String name;
  private int quantity;
  private double price;

  public Item(String name, int quantity, double price){
    this.name=name;
    this.quantity=quantity;
    this.price=price;
  }
}

public class Receipt{
   private ArrayList<Item> items = new ArrayList<Item>();

    public boolean addItem(Item item){
      if(item.getQuantity() <= 0){
        ...
        return false;
      }
      else{
            items.add(item);
        }
     }
}
0
On

You need to do 2 things first you need to make sure you have an Item. The [] is just for dereferencing (so to say access the memory location and not the reference to the array). You need to create an Item to add. The second thing you need to do is to make sure there is space. You are not allowed to access memory not reserved by the array.

public class Receipt {
    private int nItems;
    private Item[] items;

    Receipt() {
        nItems = 0;
        items = new Item[10]; // Set initial size
    }

    /**
        Set initial size of array
    */
    Receipt(int initSize) {
        if (initSize <= 0) {
            throw new IllegalArgumentException("initSize must be larger than 0");
        }
        nItems = 0;
        items = new Item[initSize]; // Set initial size
    }

    public void addItem(Item item) {
        reserve();
        items[nItems] = item;
        nItems++; // Bad experiences of incrementing while dereferencing
    }

    /**
        Make sure there is enough space in items to add an ingredient
    */
    private void reserve() {
        if (items.length == nItems) {
            Item [] tmp = new Item[nItems*2]; // Double size if array is full.
            for (int i=0; i<nItems; i++) { // Copy the old elements to new array
                tmp[i] = items[i];
            }
            items = tmp; // Replace the old array with the new array.
        }
    }
}
2
On
 public boolean addItem(String name, int quantity,double price)
 {
    if(quantity <= 0)
    {
     System.out.println("Item wasnt added");
     return false;
    }else{
         //you would have to create new object before adding it to array.
         item tempItem=new item(name,quantity,price);
         items[nItem++]=tempItem;
          }
 }