Fraction program not working - java

I'm writing a program for school that does multiplication and division with fractions. When I run the current code, multiplying the fractions 2/4 and 4/6 give me 0/1. When I individually tested the components for the numerator/denominator for the 2/4 and 4/6 fractions, it gave me back 0 1 0 1.
Here is the output and code, with code first.
import java.util.*;
import java.util.Scanner.*;
class Fraction
{
protected static int numerator, denominator;
public static void main(String args[])
{
System.out.println("Chp. 25 LAB 1");
System.out.println();
// main commands for testing first class Fraction
Fraction f1 = new Fraction(2,4);
System.out.println("numerator of fraction1 is " + f1.getNum());
System.out.println("denominator of fraction1 is " + f1.getDen());
f1.displayFraction();
f1.alterFraction(3,6);
f1.displayFraction();
// main commands for testing second class FractionArithmetic
f1 = new Fraction(2,4);
Fraction f2 = new Fraction(4,6);
FractionArithmetic f3 = new FractionArithmetic();
f3.multFracts(f1, f2);
f3.display();
f3 = new FractionArithmetic();
f3.divFracts(f1, f2);
f3. display();
// main commands for testing second class FractionOperations
f1 = new Fraction(2,4);
f2 = new Fraction(4,6);
FractionOperations fract = new FractionOperations();
fract.multFracts(f1, f2);
fract.display();
fract.reduce();
fract.getFraction().displayFraction();
fract = new FractionOperations();
fract.divFracts(f1, f2);
fract.display();
fract.reduce();
fract.getFraction().displayFraction();
}
Fraction(int n, int d)
{
numerator = n;
denominator = d;
}
public int getNum()
{
return numerator;
}
public int getDen()
{
return denominator;
}
public void alterFraction(int n, int d)
{
numerator = n;
denominator = d;
}
public void displayFraction()
{
System.out.println("Fractioni = " + numerator + "/" + denominator);
}
}
class FractionArithmetic
{
protected Fraction fraction;
FractionArithmetic()
{
fraction = new Fraction(0, 1);
}
FractionArithmetic(int n, int d)
{
fraction = new Fraction(n, d);
}
public void multFracts(Fraction a, Fraction b)
{
// System.out.println(a.getNum() + " " + a.getDen() + " " + b.getNum() + " " + b.getDen());
fraction.alterFraction(a.getNum() * b.getNum(), a.getDen() * b.getDen());
}
public void divFracts(Fraction a, Fraction b)
{
fraction.alterFraction(a.getNum() * b.getDen(), a.getDen() * b.getNum());
}
public void display()
{
System.out.println("This is an unreduced fraction");
fraction.displayFraction();
}
public Fraction getFraction()
{
return fraction;
}
}
class FractionOperations extends FractionArithmetic
{
Fraction reducedFraction;
FractionOperations()
{
reducedFraction = new Fraction(0, 1);
}
FractionOperations(int n, int d)
{
super(n, d);
reducedFraction = new Fraction(n, d);
}
public void reduce()
{
int gcf = getGCF(reducedFraction.numerator, reducedFraction.denominator);
fraction.alterFraction(reducedFraction.numerator / gcf, reducedFraction.denominator / gcf);
}
private static int getGCF(int a, int b)
{
int gcf = 1;
a = Math.abs(a);
b = Math.abs(b);
if(a > b)
{
int dummy = b;
b = a;
a = dummy;
}
for(int i = 1; i <= b; i++)
{
if(b % i == 0 && a % i == 0)
gcf = i;
}
return gcf;
}
public void display()
{
reducedFraction.displayFraction();
fraction.displayFraction();
}
public Fraction getFraction()
{
return reducedFraction;
}
}
numerator of fraction1 is 2
denominator of fraction1 is 4
Fractioni = 2/4
Fractioni = 3/6
Fractioni = 0/1
This is an unreduced fraction
Fractioni = 0/0
Fractioni = 0/1
Fractioni = 0/1
Fractioni = 0/1
Fractioni = 0/0
Fractioni = 0/0
Fractioni = 0/0

Maybe, it's because your classes made it that it divides 2/4 by 3/6. I think that the programming is using numbers like 2/4 literally and not separately resulting in numbers such as 1 and 0 only.

Related

The Constructor Rational(String) is not found

I am having an error on line 5 in my main function... The line reads:
System.out.println( "The fractional number is " + myRational.Rational(s) );
The error that occuring is telling me
The method Rational(String) is undefined for the type Assignment13.Rational.
Any help or suggestions would be greatly appreciated.
import java.math.BigInteger;
import java.util.Scanner;
public class Assignment13 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a decimal number: ");
String s = input.next();
Rational myRational = new Rational();
System.out.println( "The fractional number is " + myRational.Rational(s) );
}
public class Rational extends Number implements Comparable<Rational> {
// Data fields for numerator and denominator
private BigInteger numerator = BigInteger.ZERO;
private BigInteger denominator = BigInteger.ONE;
/** Construct a rational with default properties */
public Rational() {
this(BigInteger.ZERO,BigInteger.ONE);
}
/** Construct a rational with specified numerator and denominator */
public Rational(BigInteger numerator, BigInteger denominator) {
BigInteger gcd = gcd(numerator, denominator);
this.numerator= (denominator.compareTo(BigInteger.ZERO) > 0 ? BigInteger.ONE :
new BigInteger("-1")).multiply(numerator.divide(gcd));
this.denominator = denominator.divide(gcd);
}
public Rational(String decimal) {
int index = (decimal.contains(".")) ? decimal.indexOf('.') : decimal.indexOf('/');
BigInteger d;
BigInteger n;
// if string is in decimal form
if (decimal.contains(".")) {
int power = decimal.substring(index + 1, decimal.length()).length();
d = new BigInteger ("Math.pow(10,power)");
n = new BigInteger(new StringBuilder(decimal).deleteCharAt(index).toString());
} else {
// if string contains '/'
n = new BigInteger(decimal.substring(0, index));
d = new BigInteger(decimal.substring (index + 1, decimal.length()));
}
BigInteger gcd = gcd(n, d);
this.numerator = ((d.compareTo(BigInteger.ZERO) > 0) ? BigInteger.ONE : new BigInteger("-1")).multiply(n).divide(gcd);
this.denominator = d.abs().divide(gcd);
}
/** Find GCD of two numbers */
private BigInteger gcd(BigInteger n, BigInteger d) {
BigInteger n1 = n.abs();
BigInteger n2 = d.abs();
BigInteger gcd = BigInteger.valueOf(1);
for (BigInteger k = BigInteger.valueOf(1); k.compareTo(n1) <= 0 && k.compareTo(n2) <= 0; k.add(BigInteger.ONE)) {
if (n1.mod(k) == BigInteger.ZERO && n2.mod(k) == BigInteger.ZERO)
gcd = k;
}
return gcd;
}
/** Return numerator */
public BigInteger getNumerator() {
return numerator;
}
/** Return denominator */
public BigInteger getDenominator() {
return denominator;
}
/** Add a rational number to this rational */
public Rational add(Rational secondRational) {
BigInteger n = numerator.multiply(secondRational.getDenominator()).add(denominator.multiply(secondRational.getNumerator()));
BigInteger d = denominator.multiply(secondRational.getDenominator());
return new Rational(n, d);
}
/** Subtract a rational number from this rational */
public Rational subtract(Rational secondRational) {
BigInteger n = numerator.multiply(secondRational.getDenominator()).subtract(denominator.multiply(secondRational.getNumerator()));
BigInteger d = denominator.multiply(secondRational.getDenominator());
return new Rational(n, d);
}
/** Multiply a rational number by this rational */
public Rational multiply(Rational secondRational) {
BigInteger n = numerator.multiply(secondRational.getNumerator());
BigInteger d = denominator.multiply(secondRational.getDenominator());
return new Rational(n, d);
}
/** Divide a rational number by this rational */
public Rational divide(Rational secondRational) {
BigInteger n = numerator.multiply(secondRational.getDenominator());
BigInteger d = denominator.multiply(secondRational.numerator);
return new Rational(n, d);
}
#Override
public String toString() {
if (denominator.compareTo(BigInteger.ONE) == 0)
return numerator + "";
else
return numerator + "/" + denominator;
}
#Override // Override the equals method in the Object class
public boolean equals(Object other) {
if (((this.subtract((Rational)(other))).getNumerator()).compareTo(BigInteger.ZERO) == 0)
return true;
else
return false;
}
#Override // Implement the abstract intValue method in Number
public int intValue() {
return (int)doubleValue();
}
#Override // Implement the abstract floatValue method in Number
public float floatValue() {
return (float)doubleValue();
}
public BigInteger bigIntegerValue() {
return numerator.multiply(new BigInteger("1").divide(denominator));
}
#Override // Implement the doubleValue method in Number
public double doubleValue() {
return numerator.divide(denominator).doubleValue();
}
#Override // Implement the abstract longValue method in Number
public long longValue() {
return (long)doubleValue();
}
#Override // Implement the compareTo method in Comparable
public int compareTo(Rational o) {
if (this.subtract(o).getNumerator().compareTo(BigInteger.ZERO) > 0)
return 1;
else if (this.subtract(o).getNumerator().compareTo(BigInteger.ZERO) < 0)
return -1;
else
return 0;
}
}
}
You pass the String s to a constructor of class Assignment13.Rational and call it from an instance myRational which is work. There is no reason to create a new object nor use another one for the same thing.
myRational is already Rational since the variable declaration. If you want to print a newly created object from the String s, do:
System.out.println("The fractional number is " + new Assignment13().new Rational(s));
Or better make the class static and then is accessible with:
new Rational(s)) at the same class
new Assignment13.Rational(s) from all the classes since they are public.
In both cases, you can omit the line:
Rational myRational = new Rational(); // TODO: remove
I suggest you override the method Object::toString which is while printing out to the console by default.

quadratics methods in java displaying complex roots

everyone so I'm writting a program that solves quadratics (one doubled root and two doubled roots this seems to work but somehow I can't get it to solve complex roots? any help.
import javax.swing.JOptionPane;
public class QuadMethods {
static double a=0;
static double b=0;
static double c=0;
public static void main(String[] args) {
getUserInput(); // gets values into a, b, and c
double disc = getTheDiscriminant(a,b,c);
if (disc ==0) {
displayDoubledRealRoot(a,b,c);
//} else if (disc < 0) {
//displayComplexConjugates();
} else if (disc > 0) {
displayUnequalRealRoots(a,b,c);
//} else {
//System.out.println("Help! Arithmetic has failed!");
//
}
}
public static void displayUnequalRealRoots(double a, double b, double c) {
double disc = getTheDiscriminant(a,b,c);
double r1 = (-b+Math.sqrt(disc)/ (2*a));
double r2 = (-b-Math.sqrt(disc)/ (2*a));
String s = "two roots " + r1 + " and " + r2;
JOptionPane.showMessageDialog(null, s);
}
public static void displayDoubledRealRoot(double a, double b, double c) {
String s = "One doubled root = " + (-b/(2*a));
JOptionPane.showMessageDialog(null, s);
}
public static double getTheDiscriminant(double a, double b, double c) {
return b*b - 4*a*c;
}
public static void getUserInput() {
JOptionPane.showMessageDialog(null, "Getting coeffecients for ax^2+bx+c=0");
a = getANumber("a");
b = getANumber("b");
c = getANumber("c");
}
public static double getANumber(String p) {
boolean iDontHaveANumberYet = true;
double r = 0;
do {
try {
String aStr = JOptionPane.showInputDialog("Enter \"" + p + "\"");
r = Double.parseDouble(aStr);
iDontHaveANumberYet = false;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Hey, I can't deal with that. Must enter legal number.");
}
} while (iDontHaveANumberYet);
return r;
}
}
The solution:
import javax.swing.JOptionPane;
public class QuadMethods {
static double a=0;
static double b=0;
static double c=0;
public static void main(String[] args) {
getUserInput(); // gets values into a, b, and c
double disc = getTheDiscriminant(a,b,c);
if (disc ==0) {
displayDoubledRealRoot(a,b,c);
} else if (disc > 0) {
displayUnequalRealRoots(a,b,c);
} else {
// New method
displayComplexRoots(a,b,c);
}
}
public static void displayUnequalRealRoots(double a, double b, double c) {
double disc = getTheDiscriminant(a,b,c);
double r1 = (-b+Math.sqrt(disc)/ (2*a));
double r2 = (-b-Math.sqrt(disc)/ (2*a));
String s = "two roots " + r1 + " and " + r2;
JOptionPane.showMessageDialog(null, s);
}
public static void displayDoubledRealRoot(double a, double b, double c) {
String s = "One doubled root = " + (-b/(2*a));
JOptionPane.showMessageDialog(null, s);
}
public static double getTheDiscriminant(double a, double b, double c) {
return b*b - 4*a*c;
}
// New method
public static void displayComplexRoots(double a, double b, double c) {
double disc = 4 * a * c - b * b;
double dobleA = 2 * a;
String s = "two roots (" + (-b/dobleA) + "+" + (Math.sqrt(disc)/dobleA) + "i) and ("+ (-b/dobleA) + "" + (-Math.sqrt(disc)/dobleA) + "i)";
JOptionPane.showMessageDialog(null, s);
}
public static void getUserInput() {
JOptionPane.showMessageDialog(null, "Getting coeffecients for ax^2+bx+c=0");
a = getANumber("a");
b = getANumber("b");
c = getANumber("c");
}
public static double getANumber(String p) {
boolean iDontHaveANumberYet = true;
double r = 0;
do {
try {
String aStr = JOptionPane.showInputDialog("Enter \"" + p + "\"");
r = Double.parseDouble(aStr);
iDontHaveANumberYet = false;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Hey, I can't deal with that. Must enter legal number.");
}
} while (iDontHaveANumberYet);
return r;
}
}
General solution with complex numbers:
public class Complex {
double r;
double i = 0;
public Complex(double real, double imaginary) {
this.r = real;
this.i = imaginary;
}
public Complex(double real) {
this.r = real;
}
public Complex add(Complex c){
return new Complex(r+c.r, i+c.i);
}
public Complex cross(Complex c){
return new Complex(r*c.r - i*c.i, i*c.r + r*c.i);
}
public double getR() {
return r;
}
public double getI() {
return i;
}
#Override
public String toString() {
String result = Double.toString(r);
if (i < 0) {
result += " - " + ((i != -1)?Double.toString(-i):"") + "i";
} else if (i > 0) {
result += " + " + ((i != 1)?Double.toString(i):"") + "i";
}
return result;
}
public Complex[] squareRoot(){
double r2 = r * r;
double i2 = i * i;
double rR = Math.sqrt((r+Math.sqrt(r2+i2))/2);
double rI = Math.sqrt((-r+Math.sqrt(r2+i2))/2);
return new Complex[]{new Complex(rR, rI),new Complex(-rR, rI)};
}
public static Complex[] quadraticsRoot(double a, double b, double c) {
Complex[] result = new Complex(b*b - 4*a*c).squareRoot();
Complex bNegative = new Complex(-b);
Complex divisor = new Complex(1.0d / (2 * a));
for (int j = 0; j < result.length; j++) {
result[j] = bNegative.add(result[j]).cross(divisor);
}
return result;
}
public static void main(String[] args) {
Complex[] sol = quadraticsRoot(1,-10,34);
System.out.println(sol[0]);
System.out.println(sol[1]);
}
}

having an issue converting fractions to double

For some reason I've been unable to print a fraction as a double. I can't get past it. It gives formatting errors every time. The parts giving me issues are commented. Class and driver code are below. and help is appreciated.
Class code
public class Fraction1
{
private int numerator;
private int denominator;
public void Fraction1(int n, int d)
{
this.numerator = n;
this.denominator = d;
}
public void print()
{
System.out.println(numerator + "/" + denominator);
}
public Fraction1 add(Fraction1 other)
{
int n = this.numerator * other.denominator +
this.denominator * other.numerator;
int d = this.denominator * other.denominator;
return this;
}
//public void printAsDouble()
//{
// this.printAsDouble();
// System.out.println((double)(numerator)/(double) (denominator));
//}
}
Driver code
import java.util.*;
public class FractionDriver1
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
Fraction c, d, x;
x = new Fraction();
System.out.println("Enter numerator; then denominator.");
c = new Fraction(input.nextInt(), input.nextInt());
c.print();
System.out.println();
System.out.println("Enter numerator; then denominator.");
d = new Fraction(input.nextInt(), input.nextInt());
d.print();
System.out.println("Sum:");
x.add(c).add(d);
x.print();
//x.printAsDouble();
}
}
Should be:
(double)((numerator)/(denominator))
public class Fraction1
{
private int numerator;
private int denominator;
//no return type in constructor
public Fraction1(int n, int d)
{
this.numerator = n;
this.denominator = d;
}
public void print()
{
System.out.println(numerator + "/" + denominator);
}
public Fraction1 add(Fraction1 other)
{
//Does nothing. What does saving the values in n and d give you.
//Nothing. Hence your objects numerator and denominator
//remains 0 and hence 0/0 gives your error
int n = this.numerator * other.denominator +
this.denominator * other.numerator;
int d = this.denominator * other.denominator;
return this;
}
//public void printAsDouble()
//{
// this.printAsDouble();
// System.out.println((double)(numerator)/(double) (denominator));
//}
}
x.add(c).add(d);
So x is an empty object i.e numerator and denominator = 0.
I use the add function, but it does not modify my x object and it remains the same. In the end, i call print and it should always print 0/0.
As per the error you are getting, check your command line arguments, they must be wrong.

Java NullpointerException in the main class

The problem:
After creating an array of FractionClass objects I try to give each Fraction a numerator and denominator ,by reading in a txtfile that looks like this:
11 12
7 24
2 3
5 6
7 9
...
The first number being the numerator and the second one being the denominator, to do this I use the Scanner class.
Under the readFractions-methode i placed comments where the NULLpointerexception is located.
The mainfile:
package labo2oef5;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Labo2Oef5 {
private static Breuk [] fractionArray;
private static int amountOfLines;
public static void main(String[] args) throws FileNotFoundException {
lengteBestand(); // stel amountOfLines al in
readFractions();
System.out.println(fractionArray[4].getNumerator()+" / "+ fractionArray[4].getDenominator());`
}
public static void readFractions() throws FileNotFoundException{
Scanner lezer = new Scanner(new File("breuken01.txt"));
fractionArray = new Breuk[amountOfLines];
for(int i=0; i<amountOfLines;i++){
double numerator = (double) lezer.nextInt();
double denominator = (double) lezer.nextInt();
fractionArray[i].setNumerator(numerator); // HERE IT GOES WRONG, THE NULLPOINTEREXCEPTION IS HERE
fractionArray[i].setDenominator(denominator);// THIS LINE SUFFERS AS WELL FROM THE NULLPOINTEREXCEPTION
lezer.nextLine();
}
}
public static int lengteBestand() throws FileNotFoundException{
Scanner lezer = new Scanner(new File("breuken01.txt"));
amountOfLines=0;
while(lezer.hasNextLine()){
amountOfLines++;
lezer.nextLine();
}
return amountOfLines;
}
}
The Breuk(is dutch for Fraction) class:
package labo2oef5;
public class Breuk {
private double numerator, denominator;
public Breuk() {
numerator = 0;
denominator = 1;
}
public Breuk(double numerator, double denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
#Override
public String toString() {
String breuk = numerator + "/" + denominator;
if (numerator == 0) {
breuk = "0";
}
return breuk;
}
private static double grootsteGemeneDeler(double a, double b) {
if (a < 0 || b < 0) {
return grootsteGemeneDeler(Math.abs(a), Math.abs(b));
}
if (b == 0) {
return a;
}
if (a < b) {
return grootsteGemeneDeler(b, a);
}
if (a % b != 0) {
return grootsteGemeneDeler(b, a % b);
} else {
return b;
}
}
public String normaliseer() {
double numerator2 = numerator / (grootsteGemeneDeler(numerator, denominator));
double denominator2 = denominator / (grootsteGemeneDeler(numerator, denominator));
return numerator2 + "/" + denominator2;
}
public double decimaleVorm() {
double decim = (double) numerator / denominator;
System.out.println(decim);
return decim;
}
public boolean isGroterDan(Breuk br) {
if (this.decimaleVorm() > br.decimaleVorm()) {
return true;
} else {
return false;
}
}
public void vermeerderBreuk(Breuk br) {
this.numerator = this.numerator * br.denominator + this.denominator * br.numerator;
this.denominator = this.denominator * br.denominator;
}
public void produkt(Breuk br, Breuk breu) {
numerator = br.numerator * breu.numerator;
denominator = br.denominator * breu.denominator;
}
public void setNumerator(double numerator) {
this.numerator = numerator;
}
public void setDenominator(double denominator) {
this.denominator = denominator;
}
public double getNumerator() {
return numerator;
}
public double getDenominator(){
return denominator;
}
}
Both answers are the right answer ,I just had to add this code underneath their answer as well:
if (lezer.hasNextLine()) {
lezer.nextLine();
}
fractionArray[i] is null, so it throws NullPointerException.
I think that you should do it like that:
fractionArray[i] = new Breuk();
fractionArray[i].setNumerator(numerator);
fractionArray[i].setDenominator(denominator);
Try this:
public static void readFractions() throws FileNotFoundException{
Scanner lezer = new Scanner(new File("breuken01.txt"));
fractionArray = new Breuk[amountOfLines];
for(int i=0; i<amountOfLines;i++){
double numerator = (double) lezer.nextInt();
double denominator = (double) lezer.nextInt();
fractionArray[i] = new Breuk(numerator, denominator);
// Creating an array of references leaves them all null until you point them to something non-null by calling new
lezer.nextLine();
}
}

Why am I getting the wrong boolean returned when all other instances are correct?

Here's my Rational class:
package lab18f;
import static java.lang.System.*;
class Rational implements Comparable<Rational>
{
//add two instance variables
private int num, den;
//write two constructors
public Rational ()
{
num = 1;
den = 1;
}
public Rational (int numer, int deno)
{
num = numer;
den = deno;
}
//write a setRational method
public void setRational(int numer, int deno)
{
num = numer;
den = deno;
}
//write a set method for numerator and denominator
public void setNumerator(int numer)
{
num = numer;
}
public void setDenominator(int deno)
{
den = deno;
}
public void add(Rational other)
{
//num1/den1 + num2/den2
//new numerator = (num1 * den2 + num2 * den1)
//new denominator = (den1 * den2)
int newNumer = (this.getNumer()*other.getDeno() + other.getNumer()*this.getDeno());
int newDeno = this.getDeno()*other.getDeno();
this.setRational(newNumer, newDeno);
reduce();
}
private void reduce()
{
int gcd = 0;
int numer = num;
int deno = den;
if(numer > deno)
gcd = gcd(numer,deno);
else if(numer < deno)
gcd = gcd(deno, numer);
else
gcd = numer;
this.setRational(num/gcd, den/gcd);
}
private int gcd(int numOne, int numTwo)
{
int one = numOne;
int two = numTwo;
int gcd = two;
if(two==0)
return one;
return gcd(two, one%two);
}
public Object clone ()
{
return new Rational(num, den);
}
//ACCESSORS
//write get methods for numerator and denominator
public int getNumer()
{
return num;
}
public int getDeno()
{
return den;
}
public boolean equals( Object obj)
{
Rational lhs = (Rational)obj;
if((getNumer()/getNumer()== lhs.getNumer()/lhs.getNumer()) && getDeno()/getNumer() == lhs.getDeno()/lhs.getNumer())
return true;
return false;
}
public int compareTo(Rational other)
{
return -1;
}
//write toString() method
public String toString()
{
return "" + getNumer() + "/" + getDeno();
}
}
and the runner class for the Rational class:
import static java.lang.System.*;
public class Lab18f
{
public static void main( String args[] )
{
Rational test = new Rational();
out.println("test = " + test);
Rational newOne = new Rational(3,4);
out.println("newOne = "+newOne);
out.println("test.equals(newOne) = "+test.equals(newOne));
newOne = (Rational)test.clone();
out.println("\n\nnewOne after test.clone() = "+newOne);
out.println("test.equals(newOne) = "+test.equals(newOne));
Rational rOne = new Rational(1,2);
Rational rTwo = new Rational(2,3);
out.println("1/2.equals(2/3) = "+rOne.equals(rTwo));
test.setRational(4,6);
out.println("2/3.equals(4/6) = "+rTwo.equals(test));
out.println("\n\nrOne = "+rOne);
out.println("rTwo = "+rTwo);
out.println("rOne.compareTo(rTwo) = "+rOne.compareTo(rTwo));
out.println("rTwo.compareTo(rOne) = "+rTwo.compareTo(rOne));
rOne.add(rTwo);
out.println("\n\nrOne.add(rTwo) = "+ rOne);
rOne.setRational(1,2);
rTwo.setRational(1,3);
rOne.add(rTwo);
out.println("\n\n1/2.add(1/3) = "+ rOne);
rOne.setRational(4,10);
rTwo.setRational(3,5);
rOne.add(rTwo);
out.println("\n\n4/10.add(3/5) = "+ rOne);
rOne.setRational(2,10);
rTwo.setRational(3,6);
rOne.add(rTwo);
out.println("\n\n2/10.add(3/6) = "+ rOne);
//1/4 + 2/8 = 1/2
rOne.setRational(1,4);
rTwo.setRational(2,8);
out.println("\n\n1/4.equals(2/8) = "+rOne.equals(rTwo));
rOne.add(rTwo);
out.println("\n\n1/4.add(2/8) = "+ rOne);
//1/6 + 2/8 = 5/12
rOne.setRational(1,6);
rTwo.setRational(2,8);
out.println("\n\n1/6.equals(2/8) = "+rOne.equals(rTwo));
rOne.add(rTwo);
out.println("\n\n1/6.add(2/8) = "+ rOne);
}
}
my issue at hand is that when I run the runner class (which obviously runs the Rational class) I have a statement like this in my output:
test = 1/1
newOne = 3/4
test.equals(newOne) = true
which clearly the fraction 1/1 does not equal 3/4
Your equals method doesn't appear to be doing what it's supposed to be doing. For one, you are doing integer division, and you are dividing the numerator by itself. Try multiplying the numerator of one and the denominator of the other and comparing it to the product of the numerator of the other and the denominator of the first one. The fractions are equal if those two products are equal.
public boolean equals(Object obj)
{
Rational lhs = (Rational) obj;
return ((getNumer() * lhs.getDeno()) == (getDeno() * lhs.getNumer()));
}

Categories

Resources