Fraction class trouble (Java) - java

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()

Related

How to import a variable from a static class

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

Java and fractions

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)

Java interfaces and downcasting

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

Constructor isn't printing as expected

public class Fraction
{
public Franction(int n, int d)
{
int num = n;
int denom = d;
}
public static void main(String[] args)
{
Fraction f1 = new Fraction(5,10);
System.out.println("Fraction = " + f1);
}
}
Hello, I'm trying to learn Java... The book I'm working out of suggests that the output of the code above should print "Fraction = 5/10", but when I try it I just receive "Fraction = Fraction#33469a69" which I assume is printing the reference to where it is stored? I understand how it is suppose to work with the constructor I just don't receive the expected output. Any help would be greatly appreciated... Thanks!
To get the desired output, you need to overload toString() method in the Franction class. This method is used to determine textual representation of the object. By default, it is ClassName#hashCode.
Also, you probably would like to store the values you receive in the constructor as fields. Right now, you store the numerator and denominator in constructor's local variables, that are destroyed as soon as the constructor exits.
Try something like this:
public class Fraction
{
private final int num
private final int denom;
public Franction(int n, int d)
{
this.num = n;
this.denom = d;
}
#Override
String toString()
{
return String.format("%d/%d", num, denom);
}
public static void main(String[] args)
{
Fraction f1 = new Fraction(5,10);
System.out.println("Fraction = " + f1);
}
}
You need to override the toString method for the same
public String toString(){
StringBuilder stringToReturn = new StringBuilder();
stringToReturn.append(this.num);
stringToReturn.append("/");
stringToReturn.append(this.denom);
return stringToReturn.toString();
}
You have to override the toString() function in your Fraction class.
As per docs of toString()
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object.
So
Fraction#33469a69 is the textual representation of Fraction class.
To get the required output, write the logic in overridden toString method in Object class and return the string there.
A simple toString implementation looks like
#Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append(this.someMemeber); //will be in String format
result.append(this.someMemeber);
return result.toString();
}
Try this
public class Fraction
{
private int num;
private int denom;
public Franction(int n, int d)
{
num = n;
denom = d;
}
public int getNum()
{
return num;
}
public int getDenom()
{
return denom;
}
public static void main(String[] args)
{
Fraction f1 = new Fraction(5,10);
System.out.println("Fraction = " + f1.getNum() + "/" + f1.getDenom());
}
}
Alternative (Better way to do this)
public class Fraction
{
private int num;
private int denom;
public Franction(int n, int d)
{
num = n;
denom = d;
}
public int getNum()
{
return num;
}
public int getDenom()
{
return denom;
}
#Override
public String toString(){
return (f1.getNum() + "/" + f1.getDenom());
}
public static void main(String[] args)
{
Fraction f1 = new Fraction(5,10);
System.out.println("Fraction = " + f1 );
}
}
You need to study more about encapsulation , the Object class and the toString() method.
Happy Coding :)
Try the following:
public class Fraction {
private final int num;
private final int denom;
public Fraction(int num, int denom) {
this.num = num;
this.denom = denom;
}
#Override
public String toString() {
return num + "/" + denom;
}
public static void main(String[] args) {
Fraction f1 = new Fraction(5, 10);
System.out.println("Fraction = " + f1);
}
}
You have to store the values in the object you create. Then override the toString method of Object to get your desired output.
Output:
Fraction = 5/10
All you are doing is printing out the Object.
If you want to print the contents of the Object you will to create a toString method in you class.
see http://www.javapractices.com/topic/TopicAction.do?Id=55

Why aren't the values of these variables being set properly by the methods getFraction1 and getFraction2?

I have tried to write TestFraction in such a way that the main method calls on the methods getFraction1 and getFraction2 to create two Fractions: fr1 (a/b) and fr2 (a/b). getFraction1 and getFraction2 prompt the user for two integers, a and b, and call on getNumber to capture these integers. Fraction then performs calculations on fr1 and fr2. The problem is, when I run TestFraction, the values of a and b are left at 1, which is what they're set to in Fraction. Can anyone give me a hint as to why getFraction1 and getFraction2 aren't actually passing the values of a and b into fr1 and fr2?
Here is my code for TestFraction:
package Fraction;
import java.io.*;
import java.util.*;
public class TestFraction
{
static Scanner console = new Scanner (System.in);
private static int getNumber() throws InputMismatchException
{
return console.nextInt();
}
private static Fraction getFraction1()
{
int a=1, b=1;
Fraction frac = new Fraction ();
while (true) {
// prompt to enter a numerator and a denominator
System.out.println("Input 1st fraction numerator and denominator");
// input the numerator and the denominator using getNumber()
try {
a = getNumber();
b = getNumber();
}
catch (Exception e)
{
System.out.println("Exception: "+e.toString());
console.nextLine();
continue;
}
return frac;
// return new Fraction if OK
// otherwise print an error message
}
}
private static Fraction getFraction2()
{
int a=1, b=1;
Fraction frac = new Fraction ();
while (true) {
// prompt to enter a numerator and a denominator
System.out.println("Input 2nd fraction numerator and denominator");
// input the numerator and the denominator using getNumber()
try {
a = getNumber();
b = getNumber();
}
catch (Exception e)
{
System.out.println("Exception: "+e.toString());
console.nextLine();
continue;
}
return frac;
// return new Fraction if OK
// otherwise print an error message
}
}
public static void main(String[] args)
{
Fraction fr1 = new Fraction ();
fr1 = getFraction1();
Fraction fr2 = new Fraction ();
fr2 = getFraction2();
Fraction res = new Fraction();
// define other variables including res and fr2
res = Fraction.add (fr1, fr2);
System.out.println(fr1+" + "+fr2+" = "+res);
res = Fraction.subtract (fr1, fr2);
System.out.println(fr1+" - "+fr2+" = "+res);
res = Fraction.multiply (fr1, fr2);
System.out.println(fr1+" * "+fr2+" = "+res);
res = Fraction.divide (fr1, fr2);
System.out.println(fr1+" / "+fr2+" = "+res);
res = Fraction.lessThan (fr1, fr2);
System.out.println(fr1+" "+res+" "+fr2);
// test subtract, multiply, divide, lessThan methods
// each test has to print a description, a result,
// and, possibly, a error message if the calculation fails
}
}
And here is Fraction:
package Fraction;
public class Fraction
{
protected int a;
protected int b;
public Fraction()
{
a = 1;
b = 1;
}
public Fraction (int a, int b)
{
this.a=a;
this.b=b;
}
public int getNumerator()
{
return a;
}
public int getDenominator()
{
return b;
}
public void setNumerator(int a)
{
this.a=a;
}
public void setDenominator(int b)
{
this.b=b;
}
public String toString ()
{
return a+"/"+b;
}
public int gcd(int a, int b)
{
//ToDo implement Euclide algorithm
if (b==0) return a;
return gcd(b, a%b);
}
public void lowestTerms()
{
int g=gcd(a,b);
a=a/g;
b=b/g;
}
public static Fraction add(Fraction first, Fraction second)
{
Fraction result = new Fraction();
result.setNumerator(first.getNumerator()*second.getDenominator()
+ first.getDenominator()*second.getNumerator());
result.setDenominator(first.getDenominator()*second.getDenominator());
result.lowestTerms();
return result;
}
//ToDo methods subtract, multiply, divide, lessThan
public static Fraction subtract(Fraction first, Fraction second)
{
Fraction result = new Fraction();
result.setNumerator(first.getNumerator()*second.getDenominator()
- first.getDenominator()*second.getNumerator());
result.setDenominator(first.getDenominator()*second.getDenominator());
result.lowestTerms();
return result;
}
public static Fraction multiply(Fraction first, Fraction second)
{
Fraction result = new Fraction();
result.setNumerator(first.getNumerator()*second.getNumerator());
result.setDenominator(first.getDenominator()*second.getDenominator());
result.lowestTerms();
return result;
}
public static Fraction divide(Fraction first, Fraction second)
{
Fraction result = new Fraction();
result.setNumerator(first.getNumerator()*second.getDenominator());
result.setDenominator(first.getDenominator()*second.getNumerator());
result.lowestTerms();
return result;
}
public static Fraction lessThan(Fraction first, Fraction second)
{
if (first.getNumerator()*second.getDenominator() <=
first.getDenominator()*second.getNumerator()){
return first;
}
else {
return second;
}
}
}
You must use the Faction(int, int) constructor instead of Fraction() constructor:
Fraction frac = new Fraction ();
must be
Fraction frac = null;
//later in the code once you have a and b variables set and no exceptions...
frac = new Fraction (a, b);
OR use the setters:
frac.setNumerator(a);
frac.setDenominator(b);
before returning frac variable.
Looks like you are not setting the values you read from the console
a = getNumber();
b = getNumber();
frac.setNumerator(a);
frac.setDenominator(b);
by default a and b are set to 1, when you say
Fraction frac = new Fraction();
because the Fraction default constructor is defined like this
public Fraction()
{
a = 1;
b = 1;
}

Categories