Create a GroceryItem class with fields for a description (e.g., “Milk”) and price (e.g., 3.99)


Create a GroceryItem class with fields for a description (e.g., “Milk”) and price (e.g., 3.99); include get/set methods and at least one constructor.

Next, write a program that creates at array of 5 GroceryItem objects and fills it with reasonable data. With that array:

  • Output the name and price of each item in the array
  • Calculate and output the total price of all items in the array

Note: you should use a traversal (loop) to access the array elements.

Points to hit

  • Array- Creates and fills an array of GroceryItem objects as directed
  • Loop – uses loop(s) to traverse an array.
  • Total price – Correctly calculates and displays the total price
  • Output – Correctly outputs description and price of each item
  • GroceryItem class – GroceryItem class implemented as directed, in keeping with OOP standards and practices


class GroceryItem{
    private String description;
    private double price;

    public GroceryItem(String description, double price) {
        this.description = description;
        this.price = price;

    public String getDescription() {
        return description;

    public void setDescription(String description) {
        this.description = description;

    public double getPrice() {
        return price;

    public void setPrice(double price) {
        this.price = price;

    public String toString() {
        return "GroceryItem{" +
                "description='" + description + '\'' +
                ", price=" + price +

class Main{
    public static void main(String[] args) {
        GroceryItem items[] = new GroceryItem[5];
        items[0] = new GroceryItem("Salt",20);
        items[1] = new GroceryItem("Onions",40);
        items[2] = new GroceryItem("Chillis",15);
        items[3] = new GroceryItem("Oil",130);
        items[4] = new GroceryItem("Tomatos",15);
        double totalPrice = 0;
        for(GroceryItem item : items){
            System.out.println(item.getDescription()+" "+item.getPrice());
            totalPrice += item.getPrice();
        System.out.println("Total price is "+totalPrice);


Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.