×

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

Types of Events in Java

One of Java's key ideas is the principle of an event. Events in Java are activities that result in a change in the state or behavior of an object. The...

4 minutes read.

How to Import Packages in Java

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Cosmic Superclass in Java

The parent class of all Java classes is the Object class. The Java Object class is the parent of all Java classes, whether directly or indirectly. The Object class is...

6 minutes read.

Java Project Ideas

When it comes to constructing projects, Java is regarded as one of the best languages and is also one of the most paid. Java excels in any application, whether it...

10 minutes read.

Sorting Algorithms in Java

Sorting Algorithms in Java Sorting is the technique that puts the elements of an array or list either in descending or ascending order. For example, take an array A, whose elements...

3 minutes read.

Comparator vs Comparable in Java

Comparator Vs Comparable in Java In Java, sorting of primitive data types can be done using different inbuilt functions that are available. But for sorting the collection of objects or types...

4 minutes read.

C# vs Java

Difference Between C# and Java C# and Java both languagesare popularly used programming languages. They both are derived from C/C++ programming and follow Object Oriented Programming approach. Even so, both these...

4 minutes read.

Hidden classes in Java

There specifically are some APIs available in the market that generally is harmful to be used in our programs specifically literally, and until JDK 15, there, for all intents and...

4 minutes read.

How to initialize string array in Java

In this tutorial, we will learn how the string array is initialized in java. The initialization of string array in the java by using the NEW (it creates the object for...

3 minutes read.

Java 16

Java 16 is the most recent short-term incremental release, based on Java 15, and it was released on March 16, 2021. Records and sealed classes are just two of the...

11 minutes read.

AES 256 Encryption in Java

Now a days, security has grown in importance. Java programming supports a variety of encryption and hashing methods, which offers security for data transport and communication among various nodes. In...

4 minutes read.

Median Of Stream Of Running Integers in Java

An integer array is given to us. Compute the median of the elements traversed so far in the input array. For the sake of simplicity, assume that there are no...

10 minutes read.

Java Append Data to File

When writing data to a file using the classes within the java.io package, its file will often be overwritten, meaning that any existing data will be removed and new data...

4 minutes read.

Swapping Program in Java

Swapping Program in Java The swapping program in Java is used to interchange the values of the two variables. For example, if X = 12 and Y = 24, then the...

4 minutes read.

Centered Square Numbers in Java

In this tutorial, we will understand how to check the number is a centered square number. It is one of the prevalent interview questions of IT companies. Firstly, we will...

3 minutes read.

HttpURLConnection

HttpURLConnection Protocol It is a standard set of rules that allow electronic devices to communicate with each other. The http protocol The http protocol is for data communication, distributing, collaborating, hypermedia information systems, on the World Wide...

5 minutes read.

How to convert double to String in Java

How to Convert double to String in Java It is used when we want to convert double primitive to String type. There are two methods to convert double to String. Using String.valueOf()...

2 minutes read.

Minimum XOR value pair in Java

In this section, you will discuss about minimum XOR value pair in Java. The objective is to enforce a value that indicates the least XOR values of the two numbers from...

4 minutes read.

Java Comparator Interface

Java comparator interface is used in a situation when we have to sort an object which does not implement Comparable or do sorting in a different way than the Comparable....

1 minute read.

Java Swing Time Picker

Prerequisites In this tutorial, we will learn the time picker in java swing. Before learn time picker, we should learn about java swing. Java Swing Introduction The Java Foundation Classes include Java Swing....

5 minutes read.