Hi guys, long time lurker for information and tips in java.
I'm making a java fraction calculator in my HS CSCI class, and I when I showed my work to my teacher he says the calculator does not show accurate calculations. He wouldn't tell me what was wrong, though, and I was wondering if you guys could help me pinpoint the problem and how I can fix them? Thanks.
import javax.swing.JOptionPane;
public class Lab08bst
{
public static void main (String args[])
{
String strNum1 = JOptionPane.showInputDialog("Enter Numerator 1");
String strDen1 = JOptionPane.showInputDialog("Enter Denominator 1");
String strNum2 = JOptionPane.showInputDialog("Enter Numerator 2");
String strDen2 = JOptionPane.showInputDialog("Enter Denominator 2");
int num1 = Integer.parseInt(strNum1);
int den1 = Integer.parseInt(strDen1);
int num2 = Integer.parseInt(strNum2);
int den2 = Integer.parseInt(strDen2);
Rational r1 = new Rational(num1,den1);
Rational r2 = new Rational(num2,den2);
Rational r3 = new Rational(1,1);
Rational r4 = new Rational(1,1);
Rational r5 = new Rational(1,1);
Rational r6 = new Rational(1,1);
r3.product(r1,r2);
r4.divide(r1,r2);
r5.add(r1,r2);
r6.subtract(r1,r2);
JOptionPane.showMessageDialog(null,r1.getRational() + " * " + r2.getRational() + " = " + r3.getRational() + "\n" + r1.getRational() + " / " + r2.getRational() + " = " + r4.getRational() + "\n" + r1.getRational() + " + " + r2.getRational() + " = " + r5.getRational()+ "\n" + r1.getRational() + " - " + r2.getRational() + " = " + r6.getRational());
System.exit(0);
}
}
class Rational
{
private int num;
private int den;
private int firstNum;
private int firstDen;
public Rational(int n, int d)
{
num = n;
den = d;
firstNum = n;
firstDen = d;
reduce();
}
public int getNum()
{
return num;
}
public int getDen()
{
return den;
}
private int getGCF(int n, int d)
{
int rem = 0;
int gcf = 0;
do
{
rem = n % d;
if (rem == 0)
gcf = d;
else
{
n = d;
d = rem;
}
} while(rem != 0);
return gcf;
}
void reduce()
{
int gcf = getGCF(firstNum, firstDen);
num = firstNum / gcf;
den = firstDen / gcf;
}
void product(Rational a, Rational b)
{
int gcf = getGCF(firstNum, firstDen);
num = a.num * b.num;
den = a.den * b.den;
}
void divide(Rational a, Rational b)
{
int gcf = getGCF(firstNum, firstDen);
num = a.num / b.num;
den = a.den / b.den;
}
void add(Rational a, Rational b)
{
int gcf = getGCF(firstNum, firstDen);
num = a.num + b.num;
den = a.den + b.den;
}
void subtract(Rational a, Rational b)
{
int gcf = getGCF(firstNum, firstDen);
num = a.num - b.num;
den = a.den - b.den;
}
public double getDecimal()
{
return (double)num / den;
}
public String getRational()
{
return num + "/" + den;
}
public String getOriginal()
{
return firstNum + "/" + firstDen;
}
}