Calculate Total Expenses in Java


while purchasing certain items, a discount of 10% is offered if the quantity purchased is more than 100. If quantity and price per item are input through the keyboard, write a program to calculate the total expenses


  • The program starts by importing the Scanner class from the java.util package, which allows the user to enter input from the console.
  • Next, the main method is defined, which is the entry point of the program. Inside the main method, a new Scanner object is created to read input from the console. Then, the user is prompted to enter the quantity purchased using the System.out.print statement. The input is read using the nextInt method of the Scanner class and stored in an integer variable qty.
  • The user is then prompted to enter the amount per item using the System.out.print statement. The input is read using the nextFloat method of the Scanner class and stored in a float variable amt.
  • Next, the program calculates the total expenses of the purchase using the formula:
    • Total Expenses = Quantity Purchased * Amount Per Item
  • If the quantity purchased is greater than 100, then a 10% discount is applied to the total expenses. This is done by subtracting 10% of the total expenses from the total expenses using the following formula:
    • Total Expenses with Discount = Total Expenses - (Total Expenses * 0.1)
  • After calculating the total expenses, the program displays the result to the console using the System.out.println statement.

Source Code

import java.util.Scanner;
class Total_Expenses
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		System.out.print("Enter the Quantity Purchased : ");
		int qty = input.nextInt();
		System.out.print("Enter the Amount Per Item : ");
		float amt = input.nextFloat();
		float exp;
		if(qty>100)
		{			
			exp = qty * amt; 
			exp = exp-(exp * 0.1f);
		}
		else
		{
			exp = qty * amt; 
		}		
		System.out.println("Total Expenses is : "+exp);
	}
}

Output

Enter the Quantity Purchased : 12
Enter the Amount Per Item : 127
Total Expenses is : 1524.0

Example Programs