×

Shopping Bill in Java

Java Shopping Bill

Here in this program, we are about to create a JAVA class called Products which will have some properties or attributes like prod_name (Product Name ), qty (quantity), prod_price (Price per item) and lastly, total_prod_price (Total price of the product). Those properties or attributes of the class have been declared private, so no one outside of the class can access them directly. To create an object, only one constructor is used, which will initialize all the data members of the Products class. At the end of the application, we are using the display() function, having some printing formats to print all the properties or attributes of the Products class before displaying the result.

Now, let's develop a java program for shopping bills, and after that, we will discuss the program code. We will use Arraylist and List of the Java Collection classes in this program.

package com.java.shop;


import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;


classProducts{
// attributes of the Products
  privateString prod_name;
  privateint qty;
  privatedouble prod_price;
  privatedouble total_prod_price;


  // constructor
  Products(String prod_name,int qty,
double prod_price,double total_prod_price){
    this.prod_name = prod_name;
    this.qty = qty;
    this.prod_price = prod_price;
    this.total_prod_price = total_prod_price;
  }


  // getter methods
  publicString get_prod_name(){
    return prod_name;
  }
  publicint get_Qty(){
    return qty;
  }
  publicdouble get_prod_price(){
    return prod_price;
  }
  publicdouble get_total_prod_price(){
    return total_prod_price;
  }


  //  Display Format function 
  publicstaticvoid display_Format(){
    System.out.print(
        "\nName      qty    prod_price   Total prod_price\n");
  }


  // display
  publicvoid display(){
    System.out.format("%-8s %7d %9.2f %9.2f\n", 
         prod_name, qty, prod_price, total_prod_price);
  }
}


publicclassShopping_Bill{
  publicstaticvoid main(String[] args){
    
    // variables
    String Products_Name =null;
    int qty =0;
    double prod_price =0.0;
    double total_prod_price =0.0;
    double overAll_prod_price =0.0;
    char user_choice ='\0';


    // Creating a scanner class object with the help of the new Keyword.
    Scanner scan =newScanner(System.in);


    List<Products> Products =newArrayList<Products>();


    do{
      // reading the input values from the user
      System.out.println("Enter Products details,");
      System.out.print("Name: ");
      Products_Name = scan.nextLine();
      System.out.print("qty: ");
      qty = scan.nextInt();
      System.out.print("prod_price (per item): ");
      prod_price = scan.nextDouble();


      // Calculating the total price of the product.
      total_prod_price = prod_price * qty;


      // calculating the  overall price of the product.
      overAll_prod_price += total_prod_price;


      // creating a Products class object and adding it to the list
      Products.add(newProducts(
          Products_Name, qty, prod_price, total_prod_price));


      // ask whether to continue or not??
      System.out.print("Wanna to add more item? (yes or no): ");
      user_choice = scan.nextLine();


 
    }while(user_choice ==“yes”|| user_choice ==“YES”);


    // display all Products with their properties
    Products.display_Format();
    for(Products p: Products){
      p.display();
    }


    // overall prod_price
    System.out.println("\nTotal prod_price = "+ overAll_prod_price);


    // close Scanner
    scan.close();
  }


}

Discussion:-

In the Products class, we have used getter methods namely get_prod_name(), get_prod_price(), get_Qty() and get_total_prod_price() to get their respective values since they are declared private inside the class. To set the properties or attribute values, we are using the constructor, and we are not modifying the properties of the class after taking the input from the user. Therefore, we are not using any setter function. To display the product details rather than overriding the toString() methods, we are using the format() method. The format(() work exactly the same like printf() in C, and we can also use printf in Java. System.out.println("....") and System.out.format(".....") both works very similarly.

In the Products class, we have taken all the required attributes value of the class and then created a scanner class object to read the input values from the user. To make the product size dynamic, we are using a collection rather than a regular array. We are using the do-while loop to repeat the process, which will continue until you want. In the do-while loop, first, we are reading all the input values from the user (name, quantity, and price per item). Then we calculate the total price and add it to the overall cost.

Now, using those four properties or attributes, create an object of the Products class and add it to the collection. After that, I asked them, the user, to continue. In the end, all the product details are displayed, and the overall price is displayed.


Related Topics

Difference between String and Char Array in Java

We are heading to examine some significant differences between String and Character arrays. Both char arrays and String hold the series of characters and are utilised as a cluster of...

3 minutes read.

Mutable class in Java

A language for object-oriented programming is Java. Because this is an object-oriented language of programming, all of its mechanisms and methods are based on objects. Java has a concept of...

6 minutes read.

Prime Number Program in Java

Prime Number Program in Java using for loop A natural number which is greater than 1 and has only two factors the number itself and 1 is called prime number. In...

2 minutes read.

What’s new in Java 12

On March 19th, 2019, the Java 12th edition was released. After releasing this edition, they have decided to release every new edition every six months. This version is the advanced...

5 minutes read.

Java gc()

Garbage collection Java language provides different ways to perform the task of memory management. In Java, objects are declared and assigned references. Once lifeof an object is completed it is dereferenced...

4 minutes read.

Why String in Immutable in Java?

Why String in Immutable in Java Immutable means unchangeable or unmodifiable.  Strings in Java are immutable, it means once a string is created, it cannot be modified or changed. Any change...

2 minutes read.

Java Garbage Collection

Java Garbage Collection In Java, unreferenced objects are treated like garbage. The process of reclaiming the unused memory during runtime automatically is known as the Java Garbage Collection.In other words, the...

4 minutes read.

Java Exception Propagation

Java Exception Propagation When an exception is being thrown from the peak of the stack and not getting caught, it runs down the stack to the previous method, which is sitting...

3 minutes read.

Two Decimal Places Java

When a double data type is used in Java before a variable, this indicates 15 digits after decimal point. However, there are situations when we only require 2 decimal places...

4 minutes read.

Java Clone Array

We frequently need to copy an array to back up its original components. We have a few unique numbers and strings, including Armstrong numbers, palindrome numbers, and palindrome strings. To...

4 minutes read.

Java Substring

What is a substring in Java? Here by the name  " substring " itself, we can easily come to know it is a part of a string or a subset of...

4 minutes read.

FizzBuzz Program in Java

FizzBuzz is a well-known children's game. This game helps children learn division. The FizzBuzz game is becoming a popular programming question, appearing frequently in Core Java interviews. This section will...

3 minutes read.

Can we override Private Method in Java

In this article we will learn the concept of override, private method in java and we will now whether we can override private method in java or not. Override in Java Any...

3 minutes read.

Java Byte Keyword

Byte: The Keyword Byte in Java programming language is a primitive data type.Digital content that is most used for eight bits is called as a byte.The Java Byte Keyword is used...

3 minutes read.

Java Integer min() method

The min()  method of Integer class returns the smaller of two int values. It returns the same result as by calling Math.min.  Syntax public static int min(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

Java Math tan() Method

The tan() method of Java Math class returns the trigonometric tangent of the specified angle. Syntax: public static double tan(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The tan() method...

2 minutes read.

All the important string methods in Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Java Math abs() Method

The abs() method of Math class returns the absolute value of the argument where the argument can be int, double, float, long. Syntax public static int abs(int a) public static float abs(float a) public...

2 minutes read.

Java Try Resource

In Java, a try argument that specifies one or more resources is known as a try-with-resources statement. When your program is finished utilizing an object, it must be closed, which...

4 minutes read.

Example of Static import in Java

Static keyword Java's static keyword is mainly used to control memory. Variables, methods, blocks, and nested classes are compatible with the static keyword. Instead of an instance, the static keyword is...

3 minutes read.