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.
Related
I have a class Fraction with the arithmetic operations for fractions. Here is an abstract of my class Fraction. (I've included only method of addition.)
package com.company;
import java.util.Scanner;
public class Fraction {
private int num; // numerator
private int denom; // denominator
public Fraction() {
super();
}
public Fraction(int num, int denom) {
super();
this.num = num;
this.denom = denom;
if (denom == 0) {
this.denom = 1;
}
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public int getDenom() {
return denom;
}
public void setDenom(int denom) {
if (denom > 0) {
this.denom = denom;
}
}
public void inputFraction() {
Scanner innum = new Scanner(System.in);
System.out.println("Input numerator: ");
num = innum.nextInt();
Scanner indenom = new Scanner(System.in);
System.out.println("Input denominator: ");
denom = indenom.nextInt();
}
public String toString() {
return num + "/" + denom;
}
// addition
public Fraction add(Fraction f2) {
int num2 = f2.getNum();
int denom2 = f2.getDenom();
int num3 = (num * denom2) + (num2 * denom);
int denom3 = denom * denom2;
Fraction f3 = new Fraction(num3, denom3);
f3.simplifyFraction();
return f3;
}
}
Now my second task is to make a class Calculator, which aggregates two instances of class Fraction as its attributes and create a complete set of arithmetic operations using instances of the class Fraction as operands. So, if I am correct, I basically have to use those methods from the class Fraction in my Calculator. I've attempted to do that but I do not get any output when I call for method add (from class Calculator) in main().
Here is an abstract of my Calculator class. (I've included only method of addition to give the general idea.)
package com.company;
public class Calculator {
private Fraction f1 = new Fraction();
private Fraction f2 = new Fraction();
private Fraction f;
public Calculator() {
super();
}
public Calculator(Fraction f) {
this.f = f;
}
public void input() {
f1.inputFraction();
f2.inputFraction();
}
public void view() {
f1.toString();
System.out.println("Fraction = " + f1.toString());
f2.toString();
System.out.println("Fraction = " + f2.toString());
}
public Calculator add() {
Calculator f = new Calculator(f1.add(f2));
return f;
}
}
And part of my main():
Calculator m = new Calculator();
m.input();
m.view();
System.out.println("Sum = " + m.add());
I'm assuming there are multiple places where I have gone wrong, so I'd be grateful for some advice.
Your add method is the problem here. It is returning a Calculator object and println calls that object's toString method so the toString method for Calculator is being called. The add method should not return a new Calculator but instead a new Fraction that represents your result. Then the code will print the toString method in your Fraction class which is what you want to display.
public class Calculator {
.
.
.
public Fraction add() {
return f1.add(f2);
}
}
Using Java and trying to solve the following problem, my code keeps giving this error:
"TesterClass.java:41: error: incompatible types: int cannot be converted to String
return numerator;"
The code is supposed to print out 0 and and a 1.
I have changed about everything around, I know it is a scope and access issue, just not sure where it is.
public class TesterClass
{
public static void main(String[] args)
{
Fraction f1 = new Fraction();
Fraction f2 = new Fraction(1,2);
System.out.println(f1);
System.out.println(f2.numerator / f2.denominator); //class Scope
}
}
/** Class Fraction */
class Fraction
{
// instance variables
private int numerator;
private int denominator;
// constructor: set instance variables to default values
public Fraction()
{
int d = 1;
numerator = d;
denominator = d;
}
// constructor
public Fraction(int initNumerator, int initDenominator)
{
numerator = initNumerator;
denominator = initDenominator;
}
public String toString()
{
if (denominator == 1)
return numerator;
return numerator + "/" + denominator;
}
public int getNum()
{
return numerator;
}
public int getDen()
{
return denominator;
}
}
Should print out
1
0
return numerator; in itself cannot work because the method is supposed to return a String but numeratoris of type int.
If you want to keep the distiction using if (denominator == 1) you need to manually convert numerator to a String.
You could for example do that using
return String.valueOf(numerator)
(thanks #Antonio)
public class TesterClass
{
public static void main(String[] args)
{
Fraction f1 = new Fraction();
Fraction f2 = new Fraction(1,2);
System.out.println(f1.getNum());
System.out.println(f1);
System.out.println(f2);
}
}
/** Class Fraction */
class Fraction
{
// instance variables
private int numerator;
private int denominator;
// constructor: set instance variables to default values
public Fraction()
{
int d = 1;
int n = 1;
numerator = n;
denominator = d;
}
// constructor: set instance variables to init parameters
public Fraction(int initNumerator, int initDenominator)
{
numerator = initNumerator;
denominator = initDenominator;
}
public String toString()
{
if (denominator == 1)
return String.valueOf(numerator);
return String.valueOf(numerator) + "/" + String.valueOf(denominator);
}
public int getNum()
{
return numerator;
}
public int getDen()
{
return denominator;
}
}
You also trying access private fields numerator and denominator from TesterClass class.
To solve your error you may do:
public String toString() {
if (denominator == 1)
return numerator+"";
return numerator + "/" + denominator;
}
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.
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.
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()));
}