How to aggregate methods from another class? - java

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);
}
}

Related

Issue with Scope and Access

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;
}

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.

JAVA - Use functional interface for calculations

So... this is my first post here on Stack and i'm also new into Java (into programming at all). I'm trying to make a simple commandline app that will calculate employees' profit depending of generated income. Already did it but as i'm learning functional interfaces and lambdas right now, i'd like to try use them. Down below you can find the code.
package BalanceCounter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Number of employees: ");
int empCounter = input.nextInt();
System.out.println();
List<Employee> employees = new ArrayList<>(empCounter);
for (int i = 0; i < empCounter; i++) {
employees.add(new Employee());
}
for (Employee employee : employees) {
System.out.println("Employee: " + employee.getEmpName()
+ "\nBase salary: " + employee.getEmpBaseSalary()
+ "\nProfit from income: " + employee.getEmpBonus()
+ "\n");
}
}
}
Here's Employee class with getEmpBonus() method in comment block. That's where i've tried to use functional interfaces.
package BalanceCounter;
import java.util.Scanner;
class Employee {
private String empName;
private double empBaseSalary;
private double empIncome;
private double empBonus;
Employee() {
Scanner input = new Scanner(System.in);
System.out.print("Employees name: ");
setEmpName(input.nextLine());
System.out.print("Type basic salary: ");
setEmpSalary(input.nextDouble());
System.out.print("Generated income: ");
setEmpIncome(input.nextDouble());
setEmpBonus();
System.out.println();
}
/*
* Here are all the setters
*/
private void setEmpName(String empName) {
this.empName = empName;
}
private void setEmpSalary(double empBaseSalary) {
this.empBaseSalary = empBaseSalary;
}
private void setEmpIncome(double empIncome) {
this.empIncome = empIncome;
}
private void setEmpBonus() {
if (getEmpIncome() <= 10000)
empBonus = (getEmpIncome() * 3) / 100;
else if (getEmpIncome() > 10000 && getEmpIncome() <= 20000)
empBonus = (getEmpIncome() * 2) / 100;
else empBonus = (getEmpIncome() * 1) / 100;
}
/*
* Time for the getters
*/
String getEmpName() {
return empName;
}
double getEmpBaseSalary() {
return empBaseSalary;
}
private double getEmpIncome() {
return empIncome;
}
double getEmpBonus() {
return empBonus;
}
/*
* double getEmpBonus(Calculation calculation) {
* return empBonus = calculation.calculate(this.empBonus);
* }
*/
}
And the last thing is Calculation interface.
package BalanceCounter;
public interface Calculation {
double calculate(double arg);
}
class CalcBonus implements Calculation{
public double calculate(double empBonus) {
return empBonus;
}
}
Sorry for the long post but wanted to give you all informations i have.
Also if you see some mistakes and bad habits in my code - please let me know. Kind regards.
package training;
public class Calculator {
interface IntegerMath {
int operation(int a, int b);
}
interface RealMath {
double operation(double a, double b);
}
public int operateBinary(int a, int b, IntegerMath op) {
return op.operation(a, b);
}
public double operateBinary(int a, int b, RealMath op) {
return op.operation(a, b);
}
public static void main(String... args) {
Calculator cal = new Calculator();
IntegerMath addition = (a, b) -> a + b;
IntegerMath subtraction = (a, b) -> a - b;
IntegerMath multiplication = (a, b) -> a * b;
RealMath division = (a, b) -> a / b;
System.out.println("Add: 40 + 22 = " +
cal.operateBinary(40, 22, addition));
System.out.println("Sub: 120 - 80 = " +
cal.operateBinary(120, 80, subtraction));
System.out.println("Mul: 12 * 12 = " +
cal.operateBinary(12, 12, multiplication));
System.out.println("Div: 478 / 12 = " +
cal.operateBinary(478, 12, division));
}
}
This interface :
public interface Calculation {
double calculate(double arg);
}
has the same contract that DoubleUnaryOperator :
#FunctionalInterface
public interface DoubleUnaryOperator {
double applyAsDouble(double operand);
...
}
So you don't really need to introduce a new interface for this.
You could use the built-in one.
But if you want to really stress on the name and or arguments of the method.
As a general way, look before whether built-in Functional Interfaces could not match to your requirement before creating it.
Suppose now you uncomment your method and you want to use this method :
double getEmpBonus(DoubleUnaryOperator calculation) {
return empBonus = calculation.applyAsDouble(this.empBonus);
}
Without lambda, you have to create a subclass or an anonymous class if you want to pass an implementation that doubles the bonus :
class DoubleBonus implements DoubleUnaryOperator {
public double applyAsDouble(double operand) {
return operand * 2;
}
}
The idea of the lambda is that you could inline the subclass with a lambda expression.
You could so invoke the method in this way :
double doubledBonus = getEmpBonus(empBonus->empBonus*2);
You don't need any longer of the subclass or an anonymous class.

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.

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