I have a Fraction class which implements an interface named FractionInterface. In FractionInterface I have specified a method FractionInterface add(FractionInterface secondFraction);. I am having trouble implementing this method in my Fraction class.
public class Fraction implements FractionInterface
{private int num; // Numerator
private int den; // Denominator
public int getNum()
{
return this.num;
} // end getNum
public int getDen()
{
return this.den;
} // end getDen
public FractionInterface add(FractionInterface secondFraction)
{
FractionInterface result = (num*secondFraction.getDen()+secondFraction.getNum()*den)/
(den*secondFraction.getDen());
}
}
I get an error saying "Type mismatch: cannot convert from int to FractionInterface.", I was given a hint to downcast the parameter secondFraction from FractionInterface to Fraction but i'm not sure how to do that. Could someone explain what I am doing wrong?
What do you expect this to do?
FractionInterface result = (num*secondFraction.getDen()+secondFraction.getNum()*den)/
(den*secondFraction.getDen());
The right side is a number, the left side is an object. The compiler has no way to know how to convert a number into a Fraction object.
You need a constructor in your Fraction class that accepts a numerator and denominator:
public Fraction(int numerator, int denominator) {
num = numerator;
den = denominator;
}
and then do this
FractionInterface result = new Fraction(THENUMERATOR, THEDEMONIMATOR);
which I think, for you, is
FractionInterface result = new Fraction(
(num*secondFraction.getDen()+secondFraction.getNum()*den),
(den*secondFraction.getDen());
Related
This program is supposed to create a fraction when an object is created in the main method and use other methods to add different objects. I am using a class that contains the methods for adding and multiplying the fractions. However, in the class where I have the constructor and the accessors and mutators, I also have another two methods which update the values of numerator and denominator using the methods from the previously mentioned class. How do I access the variables from said class?
This is the class with the constructor and where I am trying to import the variables:
public class Fraction {
private int numerator;
private int denominator;
public Fraction(int numerator, int denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
// Getters and setters left out for brevity
// Calculate by using the FractionMath class, then update
// the numerator and denominator from the returned Fraction
public void addFraction(Fraction other) {
}
/**
* Updates this fraction by multiplying another fraction
* #param other Fraction to multiple to existing fraction
*/
//Calculate by using the FractionMath class, then update
//the numerator and denominator from the returned Fraction
public void multiplyFraction(Fraction other) {
}
public String toString() {
return numerator + " / " + denominator;
}
}
This is the class with the methods add and multiply:
public class FractionMath {
public static Fraction add(Fraction frac1, Fraction frac2) {
int numerator = frac1.getNumerator() * frac2.getDenominator() +
frac2.getNumerator() * frac1.getDenominator();
int denominator = frac1.getDenominator() * frac2.getDenominator();
return new Fraction(numerator, denominator);
}
public static Fraction multiply(Fraction frac1, Fraction frac2) {
int numerator = frac1.getNumerator() * frac2.getNumerator();
int denominator = frac1.getDenominator() * frac2.getDenominator();
return new Fraction(numerator, denominator);
}
}
Some terminology issues here: There are no static variables in your class. There are static methods.
A static variable would be public static int someNumber = 0;
It is not a static class (Such a thing doesn't really exist in Java), but a class with static methods. There are static inner classes, but they aren't really static in the way you'd have static variables or methods.
To call a static method, you'd just use the class name and the method name, e.g.
Fraction result = FractionMath.add(frac1, frac2);
I'm trying to add three instance methods to the public interface of class 'Fraction' that all return a 'Fraction' as a result:
add, subtraction and multiplication. is it possible to change it from my current code into instance methods?
I just can't get it to work
Here is my code:
class Fraction {
private Integer numerator;
private Integer denumerator;
public Fraction(Integer numerator, Integer denumerator) {
int gcd = 1;
for (int i = 1; i <= numerator && i <= denumerator; i++) {
if (numerator % i == 0 && denumerator % i == 0)
gcd = i;
}
this.numerator = numerator / gcd;
this.denumerator = denumerator / gcd;
}
public Fraction(Integer numerator) {
this.numerator = numerator;
this.denumerator = 1;
}
public String toString() {
return numerator + "/" + denumerator;
}
public static Fraction add(Fraction f1,Fraction f2){
return new Fraction(f1.numerator*f2.denumerator+f2.numerator*f1.denumerator,f1.denumerator*f2.denumerator);
}
public static Fraction subtract(Fraction f1,Fraction f2){
return new Fraction(f1.numerator*f2.denumerator-f2.numerator*f1.denumerator,f1.denumerator*f2.denumerator);
}
public static Fraction mul(Fraction f1,Fraction f2){
return new Fraction(f1.numerator*f2.numerator,f1.denumerator*f2.denumerator);
}
}
class Main
{
public static void main(String[] arguments)
{
final Fraction HALF = new Fraction(1, 2);
final Fraction THREE_FIFTH = new Fraction(3, 5);
System.out.println(HALF.add(HALF, THREE_FIFTH).toString());
System.out.println(THREE_FIFTH.subtract(HALF, THREE_FIFTH).toString());
System.out.println(HALF.mul(HALF, THREE_FIFTH).toString());
}
}
public static Fraction add(Fraction f1,Fraction f2){
return new Fraction(f1.numerator*f2.denumerator+f2.numerator*f1.denumerator,
f1.denumerator*f2.denumerator);
}
is a class method (because of the static it does not need an instance to call "on").
Making it instance method would look like
public Fraction add(Fraction other){
return new Fraction(this.numerator*other.denumerator+other.numerator*this.denumerator,
this.denumerator*other.denumerator);
}
of course you do not actually need to write the thiss there, just they emphasize that f1 became the current object, and f2 became the single argument.
Then you could use it as
Fraction HALF = new Fraction(1, 2);
Fraction THREE_FIFTH = new Fraction(3, 5);
System.out.println(HALF.add(THREE_FIFTH));
without repeating HALF (like HALF.add(HALF,THREE_FIFTH) in the original code).
Side comment: class methods (static stuff) can be referred via the name of the class, your original code would be more conventionally called in the form Fraction.add(...):
System.out.println(Fraction.add(HALF,THREE_FIFTH));
(System.out.println() knows that it should call toString() so you do not actually need to do that yourself)
I'm very new at code, and I can't find an explanation or solution that I can understand even though I'm pretty sure this is simple. I hope I got the terms right too. What I'm confused about is:
public class Item{
public Item(int number1, int number2, int number3){
//Nothing really significant in here, just some mathematics
}
public int getNumber(){
//I want to get the values of number 1-3 here, without parameters
//or any data structures if possible.^
}
}
If anyone could please explain it to me, I would be grateful. I would've looked up more, but I spent already half a day around these kind of problems and I'm not exactly experienced.
Thank you!
If you want to be able to retrieve a value at some point, you have to store it somewhere. This is done at the initialization phase when you create a new object with the constructor. When you call a constructor, you need to store the values you need when building your object. By doing that, your object keeps the needed values number1, number2, number3. Note that if you need to store an indefinite number of numbers that are not semantically defined (eg. you only store numbers that are not an area, a price, a quantity defined by a given name) then you should maybe store them inside an array.
public class Item {
private int number1; // internal attributes
private int number2; // are initialized
private int number3; // in the constructor
public Item(int number1, int number2, int number3) { // constructor
this.number1 = number1;
this.number2 = number2; // setup internal attributes
this.number3 = number3;
}
}
Then, when calling a getter, you may fetch the stored values. Your class has now 3 new functions.
public class Item {
private final int number1;
private final int number2;
private final int number3;
public Item(int number1, int number2, int number3){
this.number1 = number1;
this.number2 = number2;
this.number3 = number3;
}
// add getter methods that only return internal attributes
// values, so that it would be impossible to modify them
// from the outside
public int getNumber1() {
return number1; // equivalent of return this.number1;
}
public int getNumber2() {
return number2;
}
public int getNumber3() {
return number3;
}
}
Hope this solves your problem.
In constructor you can initialize class's variables. These variables belong to the class' instance, so the're available in the class' method. Each object that you create with new Item(1,2,4) will have it's own set of these fields.
To get each variable, it's better to use getters.
public class Item {
private final int number1;
private final int number2;
private final int number3;
// Method with same name as class called Constructor
public Item(int number1, int number2, int number3){
this.number1 = number1;
this.number2 = number2;
this.number3 = number3;
}
public int getNumber1() {
return number1;
}
public int getNumber2() {
return number2;
}
public int getNumber3() {
return number3;
}
}
You cannot really get 3 integers in 1 integer without any data structures. Think it in a way you wanna fit 3 sim cards in your phone with 1 slot.
also the function is named getNumber() which raises the question which number?
Same as the others said you will need to store your parameters in your class in some form so you will reuse them later
So you should use something like int[] or List<Integer> or even better a custom class named for example Numbers with methods getNumber1 getNumber2 getNumber3.
Hope that helped!
When you call Item(...) you need to save the parameters in the class properties, so that you can access them later when you call getNumber()
public class Item{
private int number1;
private int number2;
private int number3;
public Item(int number1, int number2, int number3){
this.number1 = number1;
this.number1 = number2;
this.number1 = number3;
//Nothing really significant in here, just some mathematics
}
public int getNumber(){
//here you can access to this.number1, this.number2, this.number3
}
}
check the snippet code :-
import java.util.*;
public class MyClass
{
public List<Integer> setNumberList = new ArrayList<Integer>();
public void setNumbers(int number1,int number2,int number3)
{
setNumberList.add(number1);
setNumberList.add(number2);
setNumberList.add(number3);
}
public List<Integer> getNumbers()
{
return setNumberList;
}
public static void main(String args[])
{
MyClass obj = new MyClass();
obj.setNumbers(9,2,3);
List<Integer> getyourNumbers= obj.getNumbers();
//the whole data is save in your list now you can get data by iterating it as you
want
System.out.print(getyourNumbers);
}
}
An instructor recently set the task of coding a small calculator class for integers and doubles. As worded the assignment is covered by the following:
public final class Calculator {
public int add(int augend, int addend) { return augend + addend; }
public double add(double augend, double addend) { return augend + addend; }
public int subtract(int minuend, int subtrahend) { return minuend - subtrahend; }
public double subtract(double minuend, double subtrahend) { return minuend - subtrahend; }
public int divide(int dividend, int divisor) { return dividend / divisor; }
public double divide(double dividend, double divisor) { return dividend / divisor; }
public int multiply(int multiplicand, int multiplier) { return multiplicand * multiplier; }
public double multiply(double multiplicand, double multiplier) { return multiplicand * multiplier; }
}
I am wondering though, given that the methods are functionally the same if the
duplication of the functionality could be removed somehow by the use of generics?
I have tried a couple of routes to make this happen, the latest is to make the entire class generic as follows, but keep getting stuck where it comes to actually applying the mathematical operations to the variables
public class Calculator<T extends Number> {
public T add(T augend, T addend) {
// addition is the same for any number type
return augend + addend; // "operator '+' cannot be applied to 'T','T'"
}
// etc...
}
The error message, or a variant thereof, comes into play with whichever method I try... Is there a better way to do this? (with or without generics)
I don't think you can apply operators on Type T. Since during compilation this will get replaced with the object in case of unbounded Type and with the first bound in case of bounded type. Refer https://docs.oracle.com/javase/tutorial/java/generics/genTypes.html. In the below code, it would get replaced with Number but Number doesn't work with operators.
You can create an generic interface like this :
interface Calc<T extends Number>{
T add(T a, T b);
}
Now create Concrete Classes for Integer and Doubles
class IntegerCalc implements Calc<Integer>{
#Override
public Integer add(Integer a, Integer b) {
return a+b;
}
}
class DoubleCalc implements Calc<Double>{
#Override
public Double add(Double a, Double b) {
return a+b;
}
}
You did it fine! Pretty simple and reliable code. Good Job.
P.S. Think about that generics work with Object, and Integer and int is not absolutely the same thing. If you can work with a simple type, you should do it and avoid wrappers.
I am trying to store Fraction objects in an Stack of type Number and then retrieve them to perform arithmetic calculations on them, however, the objects are being converted to type Number when I put them in the stack and I cannot convert them back to type Fraction. The compilation error occurs at line 19 of the source code below. How do I fix this?
Source code:
import java.util.Scanner;
import java.util.Stack;
public class Test{
public static void main(String[] args){
String line = "3/4";
Scanner input = new Scanner(line);
Stack<Number> numbers = new Stack<>();
while (input.hasNext()){
if (input.hasNext("/")){
numbers.push(new Fraction(input.next()));
}
}
if (numbers.peek() instanceof Fraction){
Fraction rhs = numbers.pop();
System.out.println(rhs.getFraction());
}
}
}
The Fraction class exends Number because I need to be able to store Integers, Doubles, Fractions, and Complex numbers to support inter-type mathematical operations. Note that this is not the entire Fraction class, but it is all I used for the compilation of this small test program.
public class Fraction extends Number{
private int numerator;
private int denominator;
public Fraction(String s){
this.numerator = Integer.parseInt(s.substring(0, s.indexOf("/") - 1));
this.denominator = Integer.parseInt(s.substring (s.indexOf("/") + 1, s.length() - 1));
}
public String getFraction(){
String output = this.numerator + "/" + this.denominator;
return output;
}
///Methods for retrieving and changing both the numerator and the denominator
public int getNum(){
return this.numerator;
}
public int getDenum(){
return this.denominator;
}
public void setNum(int num){
this.numerator = num;
}
public void setDenum(int denum){
this.denominator = denum;
}
public int intValue(){
return (Integer) this.numerator/this.denominator;
}
public double doubleValue(){
return this.numerator/this.denominator;
}
public long longValue(){
return this.numerator/this.denominator;
}
public short shortValue(){
return 0;
}
public float floatValue(){
return 0.0f;
}
}
This has nothing to do with Fraction. If Fraction subclasses Number then you should be able to cast from Number to Fraction. So something like
Fraction rhs = (Fraction) numbers.pop()