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