Java Program to Calculate the Percentage

Introduction

Calculating the percentage is a common task in various applications, such as grading systems, financial calculations, and statistical analysis. This guide will show you how to create a Java program to calculate the percentage based on user input.

Problem Statement

Create a Java program that:

  • Takes two inputs from the user: the obtained marks and the total marks.
  • Calculates the percentage of obtained marks relative to the total marks.
  • Displays the calculated percentage.

Example 1:

  • Input: Obtained Marks = 450, Total Marks = 500
  • Output: Percentage = 90.0%

Example 2:

  • Input: Obtained Marks = 75, Total Marks = 100
  • Output: Percentage = 75.0%

Solution Steps

  1. Input the Obtained and Total Marks: Prompt the user to enter the obtained marks and the total marks.
  2. Calculate the Percentage: Use the formula Percentage = (Obtained Marks / Total Marks} * 100
  3. Display the Result: Output the calculated percentage to the user.

Java Program

import java.util.Scanner;

/**
 * Java Program to Calculate the Percentage
 * Author: https://www.javaguides.net/
 */
public class PercentageCalculator {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Step 1: Input the Obtained and Total Marks
        System.out.print("Enter the obtained marks: ");
        double obtainedMarks = scanner.nextDouble();
        System.out.print("Enter the total marks: ");
        double totalMarks = scanner.nextDouble();

        // Step 2: Calculate the Percentage
        double percentage = (obtainedMarks / totalMarks) * 100;

        // Step 3: Display the Result
        System.out.printf("Percentage = %.2f%%\n", percentage);
    }
}

Explanation

Step 1: Input the Obtained and Total Marks

  • The program prompts the user to enter the obtained marks and the total marks. These values are read as double to accommodate decimal inputs.

Step 2: Calculate the Percentage

  • The percentage is calculated using the formula Percentage = (Obtained Marks / Total Marks} * 100.
  • The result is stored in a double variable to ensure precision.

Step 3: Display the Result

  • The program outputs the calculated percentage using System.out.printf to format the result with two decimal places, followed by the % symbol.

Output Examples

Example 1:

Enter the obtained marks: 450
Enter the total marks: 500
Percentage = 90.00%

Example 2:

Enter the obtained marks: 75
Enter the total marks: 100
Percentage = 75.00%

Conclusion

This Java program efficiently calculates the percentage of obtained marks relative to the total marks. By using a simple formula and basic user input/output functions, the program is easy to understand and modify for various applications. This method can be extended to handle more complex percentage calculations or integrated into larger systems where percentage calculations are needed.

Comments