Calculating a percentage in Java is a common task that can be accomplished using simple arithmetic operations. This article will guide you through creating a Java program that calculates percentages, includes import statements, the main method, and uses the Scanner class for user input.
Table of contents
Understanding percentage calculation
The formula for calculating percentage is as follows:
Percentage = ( part / total ) x 100
Where part is the value you want to find the percentage of and total is the maximum possible value.
A classic example is trying to find the percentage after taking a school exam. Say you got 37 answers right out of a total of 40 questions, and you want to know what percentage of the questions you got right. You would divide 37 by 40 and multiply the result by 100 to get the percentage of correct answers.
Prerequisites
Before you start, be sure to have completed the Java installation on your computer (download Java). Next, open your favorite IDE or a simple text editor and create a new file named PercentageCalculator.java.
Sample code
Here is the sample Java program that demonstrates how to calculate the percentage in Java:
import java.util.Scanner;
public class PercentageCalculator {
public static void main(String[] args) {
// Create a Scanner object to read user input
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the 'part' value
System.out.print("Please enter the part value: ");
double part = scanner.nextDouble();
// Prompt the user to enter the 'total' value
System.out.print("Please enter the total value: ");
double total = scanner.nextDouble();
// Validate total to avoid division by zero
if (total == 0) {
System.out.println("Oops! Total value cannot be zero!");
return;
}
// Calculate the percentage
double percentage = (part / total) * 100;
// Display the result with a decimal value
System.out.printf("The percentage is: %.2f%%\n", percentage);
// Close the scanner
scanner.close();
}
}
Code language: Java (java)
Let’s understand the code:
- Line 1: This imports the Scanner class, which is used to get user input.
- Line 4: The main method is the entry point of the Java application.
- Line 6: This creates a Scanner object to read input from the standard input stream (keyboard).
- Lines 9-14: These lines prompt the user to enter the values for
partandtotal, and a separate variable is used to store these values. Notice that the data type isdoublewhich allows the program to perform integer division as well as fractional. - Lines 17-20: This ensures that the total value is not zero to avoid division by zero. We all know that the world could end if we divide by zero!
- Line 23: This line performs the percentage calculation.
- Line 26: It prints the calculated percentage to the console with two decimal places. Where
%.2ftells Java to format a floating-point number and use two numbers for the decimal part,%%prints a literal % symbol, and\nprints a new line character. - Line 29: This closes the
Scannerobject to free up resources.
Running the program
If you’ve written the program using an IDE, you can use the same to execute the program.
Follow these steps to run the program if you’re not using an IDE:
Save the code snippet in a file called PercentageCalculator.java. Open your command prompt or terminal, navigate to the directory where the files are saved, and compile and run each program using the following command:
javac PercentageCalculator.java
java PercentageCalculatorCode language: Bash (bash)
The program will prompt you to enter the part (numerator) and total (denominator) where the input value can be a whole number or numbers that have decimal points. It then displays the calculated percentage.
Final thoughts on how to calculate percentages in Java
Calculating a percentage in Java is straightforward. You can easily perform percentage calculations in your Java applications by following the steps and using the provided sample code. The Scanner class allows for interactive input, making your program more user-friendly. The sample program is able to perform whole or decimal number division.
Related articles
Follow our blog
Be the first to know when we publish new content.
Formula for percentage in Java
- How to Exit A Program in Java - June 16, 2024
- How to Get User Input in JavaScript - June 7, 2024
- How To Calculate Percentage In Java - June 1, 2024