Reputation:
over here I have some code that is supposed to make a constructor and some getters for my Fraction class. I'm wondering, is it possible to get both parameters in one getter? Because I'm only supposed to use only one method into obtaining both of my results.
Such as "1/2 and 3/5" for example.
import java.lang.reflect.*; import java.lang.annotation.*; import java.util.*; import java.time.*; // Please do not change or remove this line.
class Fraction {
private Integer nominator;
private Integer denominator;
public Fraction(Integer nominator, Integer denominator){
this.nominator = nominator;
this.denominator = denominator;
}
public Integer getNominator() {
return nominator;
}
public Integer getDenominator() {
return denominator;
}
}
class Main {
public static Fraction createFraction(Integer nominator, Integer denominator) {
return new Fraction(nominator, denominator);
}
public static void main(String[] arguments) {
final Fraction HALF = createFraction(1, 2);
final Fraction THREE_FIFTH = createFraction(3, 5);
System.out.println((HALF));
System.out.println((THREE_FIFTH));
}
public static String toString(Fraction fraction) {
return fraction.getDenominator() + "/" + fraction.getNominator();
}
}
Upvotes: 0
Views: 81
Reputation: 438
create a small class and return it or use an array for example something like this
class Fraction1{
private int nominator;
private int denominator;
}
public Fraction1 getDenominator() {
Fraction1 fr=new Fraction1();
fr.nominator=this.nominator;
fr.denominator=this.denominator;
return fr;
}
..............
Upvotes: 1
Reputation: 62759
First of all, great that you don't have setters and your class is functionally immutable--good start!
I would somewhat resist getting the nominator and denominator at all. You will eventually have to I'm sure, but try to avoid it.
For instance, if you were multiplying two Fractions you would simply have a Fraction.multiply(Fraction) method that returns a new Fraction, no need for getters. Anything you might want to do to the nominator/denominator you should be able to do inside the Fraction class.
As for if you really NEED to get the values (with one method):
Upvotes: 1