In this quick tutorial, we will create a Java program to calculate the percentage.
But first, let’s define how to calculate percentage mathematically.
Mathematical Formula
In mathematics, a percentage is a number or ratio expressed as a fraction of 100. It’s often denoted using the percent sign, “%”.
percentage = (x/y)*100
Java Program to Calculate the Percentage
Let’s build a Java program to calculate Student marks:
package net.javaguides.corejava;
import java.util.Scanner;
/**
* Java Program to Calculate the Percentage
* @author javaguides.net
*
*/
public class PercentageProgram {
public double calculatePercentage(double obtained, double total) {
return obtained * 100 / total;
}
public static void main(String[] args) {
PercentageProgram pc = new PercentageProgram();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter obtained marks:");
double obtained = scanner.nextDouble();
System.out.println("Enter total marks:");
double total = scanner.nextDouble();
System.out.println(
"The percentage obtained: " + pc.calculatePercentage(obtained, total));
scanner.close();
}
}
Output:
Enter obtained marks:
67
Enter total marks:
100
The percentage obtained: 67.0
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course