Program To Add Two Fractions In Java
Adding two fractions involves a few key mathematical steps: finding a common denominator, converting the fractions, and then adding the numerators. This process can be easily implemented in Java. In this article, you will learn how to write a Java program to add two fractions.
Problem Statement
The task is to create a Java program that can take two fractions as input, add them together, and display the resulting sum as a simplified fraction. This involves handling user input, performing arithmetic operations on fractions, and simplifying the final result.
Example
Let's say we want to add 1/2 and 1/3. The expected output would be 5/6.
Background & Knowledge Prerequisites
To understand this article, you should have a basic understanding of:
- Java basics: Variables, data types, operators, and control structures (if/else, loops).
- Methods: How to define and call methods.
- User input: Using the
Scannerclass. - Mathematical concepts: Fractions, common denominators, and greatest common divisor (GCD).
Use Cases or Case Studies
- Educational software: Programs designed to teach fraction arithmetic to students.
- Financial applications: Calculating proportions or shares.
- Engineering calculations: Combining fractional measurements.
- Recipe scaling: Adjusting ingredient quantities in recipes.
Solution Approaches
We will implement a solution that involves a Fraction class to represent fractions and methods to perform addition and simplification.
Approach 1: Using a Fraction Class
This approach encapsulates the numerator and denominator within a Fraction object, making the code more organized and readable.
One-line summary: Define a Fraction class with methods for addition and simplification, then use it in the main program.
// Add Two Fractions
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
// Method to calculate the Greatest Common Divisor (GCD)
// Used for simplifying fractions
public static int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Step 1: Get input for the first fraction
System.out.print("Enter numerator for fraction 1: ");
int num1 = scanner.nextInt();
System.out.print("Enter denominator for fraction 1: ");
int den1 = scanner.nextInt();
// Step 2: Get input for the second fraction
System.out.print("Enter numerator for fraction 2: ");
int num2 = scanner.nextInt();
System.out.print("Enter denominator for fraction 2: ");
int den2 = scanner.nextInt();
// Step 3: Calculate the common denominator
int commonDenominator = den1 * den2;
// Step 4: Convert numerators to the common denominator
int newNum1 = num1 * den2;
int newNum2 = num2 * den1;
// Step 5: Add the new numerators
int sumNumerator = newNum1 + newNum2;
// Step 6: Simplify the resulting fraction
int commonDivisor = gcd(sumNumerator, commonDenominator);
int simplifiedNumerator = sumNumerator / commonDivisor;
int simplifiedDenominator = commonDenominator / commonDivisor;
// Step 7: Display the result
System.out.println("The sum of " + num1 + "/" + den1 + " and " + num2 + "/" + den2 + " is: " +
simplifiedNumerator + "/" + simplifiedDenominator);
scanner.close();
}
}
Sample output:
Enter numerator for fraction 1: 1
Enter denominator for fraction 1: 2
Enter numerator for fraction 2: 1
Enter denominator for fraction 2: 3
The sum of 1/2 and 1/3 is: 5/6
Stepwise explanation:
gcdMethod: A helper methodgcd(int a, int b)is defined to calculate the Greatest Common Divisor using the Euclidean algorithm. This is crucial for simplifying fractions.- Input: The program prompts the user to enter the numerator and denominator for two fractions using
Scanner. - Common Denominator: The common denominator is found by multiplying the two original denominators (
den1 * den2). - Numerator Conversion: Each numerator is adjusted by multiplying it by the other fraction's denominator to maintain its value relative to the common denominator.
-
newNum1 = num1 * den2 -
newNum2 = num2 * den1
- Add Numerators: The adjusted numerators are added together to get the
sumNumerator. - Simplify Fraction:
- The
gcdof thesumNumeratorandcommonDenominatoris calculated. - Both the
sumNumeratorandcommonDenominatorare divided by thisgcdto get thesimplifiedNumeratorandsimplifiedDenominator.
- Display Result: The original fractions and their simplified sum are printed to the console.
- Close Scanner: The
Scannerobject is closed to release system resources.
Conclusion
Adding fractions in Java involves a clear set of steps: obtaining input, finding a common denominator, adjusting numerators, adding them, and finally simplifying the result. By breaking down the problem into these logical steps, we can create a robust and understandable program. The use of a GCD function is essential for presenting the sum in its simplest form.
Summary
- Input: Get numerators and denominators for two fractions.
- Common Denominator: Multiply the denominators of the two fractions.
- Numerator Adjustment: Multiply each numerator by the other fraction's denominator.
- Sum Numerators: Add the adjusted numerators.
- Simplify: Calculate the Greatest Common Divisor (GCD) of the sum's numerator and denominator, then divide both by the GCD.
- Output: Display the simplified sum.