## Free Data Structures and Algorithms Course

### How to calculate percentage in Java ?.

Program to demonstrate how to calculate percentage in Java

```package com.hubberspot.code;

import java.util.Scanner;

public class PercentageCalculator {

public static void main(String[] args) {

// Create two variables x and y initially assigned
// to a value 0.

double x = 0;
double y = 0;

// Create a Scanner object which takes System.in object
// this makes us read values from the console

Scanner scanner = new Scanner(System.in);

// In order to Calculate (x % of y) ?...
// We will prompt user to enter values
// of x and y

// Prompting user to enter value of x
System.out.println("Enter the value of x : ");

// Scanner objects nextDouble reads output from the console
// entered by user and stores into the double variable
x = scanner.nextDouble();

// Prompting user to enter value of y
System.out.println("Enter the value of y : ");

// Scanner objects nextDouble reads output from the console
// entered by user and stores into the double variable
y = scanner.nextDouble();

System.out.println();

System.out.println("Calculating percentage : (x % of y) : ");

// In order to calculate x percent of y
// we use the following formula and store the result
// in a variable called as result
double result = x * y / 100;

// printing the result on the console
System.out.println(x + " % of " + y + " is " + result);

System.out.println();

}

}

```

Output of the program :

© 2021 Learn Java by Examples Template by Hubberspot