Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Here\'s what it needs to do: Write a rational number calculator that repeatedly

ID: 3625782 • Letter: H

Question

Here's what it needs to do:

Write a rational number calculator that repeatedly waits for an input line and then prints the result of the calculation using your RationalNumber class (so I need to modify the code that I have provided and I need to change it so that it outputs the following). The calculator should stop once the user types “q”. Your program should behave like this:


>1/2+1/2

1/1

>1/2-1/2

0/1

> 10 / 1 * -1 / 10

-1/1

> -64 / 128 / 128 / -64

1/4

> 2 / -4 = -3 / 6

true

>q

Each line has the following format / / , so it should be easy to parse using Scanner methods. / represents a rational number, and is a single character indicating the desired operation. You may assume that every input follows this format without error.
Also needs to not use a try catch.

Here's my program:

public class RationalNumber2 {

private int num;
private int den;
public RationalNumber2(){ //Initializes to 0/1
num = 1;
den = 1;
}
public RationalNumber2(int num, int den){ //Initializes to n/d
try{this.den=den;
this.num=num;
if(den==0){
throw new IllegalArgumentException("Zero value at constructor");
}
}catch(IllegalArgumentException e){
System.out.println(e.getMessage());

}
this.reduce();
}

//public RationalNumber(RationalNumber x){//Initializes to x's values

public void add(RationalNumber2 other){ // this = this + other
this.den = this.den * other.den;
this.num = this.num * other.den + other.num * this.den;
this.reduce();
//toString();
}

public void subtract(RationalNumber2 other){ // this = this - other
this.den = this.den * other.den;
this.num = this.num * other.den - other.num * this.den;
this.reduce();
//toString ();
}

public void multiply(RationalNumber2 other){ // this = this * other
this.den = this.den * other.den;
this.num = this.num * other.num;
this.reduce();
//toString ();
}
public void divide(RationalNumber2 other){ // this = this / other
this.den = this.den * other.num;
this.num = this.num * other.den;
this.reduce();
//toString ();
}
private void reduce(){
int yes = 0;
int smaller;
int num1=this.num,den1=this.den;
if(num<0)
{ num1=-1*num;}
if(den<0)
{ den1=-1*den;}
if ( num1 < den1 ){
smaller = num1;
}else{
smaller = den1;}

for ( int div = smaller; div >= 2; div-- ){
if ( num1 % div == 0 && den1 % div == 0 ){
yes = div;
break;
}
}
if ( yes != 0 ){
num /= yes;
den /= yes;
}
}

public String toString(){ // Creates string representation
if(this.den<0&&this.num<0)
return(""+(-1*this.num)+"/"+(-1*this.den));
else if(this.den<0&&this.num>0)
return("-"+(this.num)+"/"+(-1*this.den));
else if(this.den>0&&this.num<0)
return("-"+(-1*this.num)+"/"+(this.den));
else
return(""+(this.num)+"/"+(this.den));

}
public boolean equals(RationalNumber2 other){ // Is this == other?
this.reduce();
other.reduce();
if( num == other.num && den == other.den){
return true;
}else{
return false;
}
}
}

Explanation / Answer

import java.util.Scanner;

public class RationalCalculator {

    Scanner kbd;
    private RationalNumber operand1;
    private RationalNumber operand2;
    /**
     * operation:
     * 0 : add;
     * 1 : subtract;
     * 2 : multiply;
     * 3 : divide;
     * 4 : compare;
     */
    private int operation;

    public RationalCalculator()
    {
        kbd = new Scanner(System.in);
    }
    /**
     * gets input from console line, and initializes operands and operation
     * @return true if new expression is inputed, false if user wants to quit
     */
    public boolean getInput()
    {
        String[] lineParts = kbd.nextLine().split("/");
        if(lineParts.length == 1)
            if(lineParts[0].equalsIgnoreCase("q")) return false;
        if(lineParts.length == 4) //divide case
        {
            operation = 3;
            operand1  = new RationalNumber(Integer.parseInt(lineParts[0]), Integer.parseInt(lineParts[1]));
            operand2 = new RationalNumber(Integer.parseInt(lineParts[2]), Integer.parseInt(lineParts[3]));
        }
        else //not divide
        {
            String[] midPart = lineParts[1].trim().split("\s"); //should yield 3 parts, i.e: 3, +, 4
            switch(midPart[1].trim().charAt(0)) // grab the operator
            {
            case '+':
            {
                operation = 0;
                operand1 = new RationalNumber(Integer.parseInt(lineParts[0].trim()), Integer.parseInt(midPart[0].trim()));
                operand2 = new RationalNumber(Integer.parseInt(midPart[2].trim()), Integer.parseInt(lineParts[2].trim()));
                break;
            }
            case '-':
            {
                operation = 1;
                operand1 = new RationalNumber(Integer.parseInt(lineParts[0].trim()), Integer.parseInt(midPart[0].trim()));
                operand2 = new RationalNumber(Integer.parseInt(midPart[2].trim()), Integer.parseInt(lineParts[2].trim()));
                break;
            }
            case '*':
            {
                operation = 2;
                operand1 = new RationalNumber(Integer.parseInt(lineParts[0].trim()), Integer.parseInt(midPart[0].trim()));
                operand2 = new RationalNumber(Integer.parseInt(midPart[2].trim()), Integer.parseInt(lineParts[2].trim()));
                break;
            }
            case '=':
            {
                operation = 4;
                operand1 = new RationalNumber(Integer.parseInt(lineParts[0].trim()), Integer.parseInt(midPart[0].trim()));
                operand2 = new RationalNumber(Integer.parseInt(midPart[2].trim()), Integer.parseInt(lineParts[2].trim()));
                break;
            }
            }
        }
        return true;
    }
    /**
     * adds
     */
    private void add(){ // operand1 = operand1 + operand2
        //operand1.den = operand1.den * operand2.den; //wrong output because you change den to new value,   
        operand1.num = operand1.num * operand2.den + operand2.num * operand1.den;    // but you want the old value here.
        operand1.den = operand1.den * operand2.den;
        operand1.reduce();
        //toString();
    }
    /**
     * subtracts
     */
    private void subtract(){ // operand1 = operand1 - operand2
//        operand1.den = operand1.den * operand2.den; //see add explanation
        operand1.num = operand1.num * operand2.den - operand2.num * operand1.den;
        operand1.den = operand1.den * operand2.den;
        operand1.reduce();
        //toString ();
    }

    /**
     * multiplies
     */
    private void multiply(){ // operand1 = operand1 * operand2
        operand1.den = operand1.den * operand2.den;
        operand1.num = operand1.num * operand2.num;
        operand1.reduce();
        //toString ();
    }
    /**
     * divides
     */
    private void divide(){ // operand1 = operand1 / operand2
        operand1.den = operand1.den * operand2.num;
        operand1.num = operand1.num * operand2.den;
        operand1.reduce();
        //toString ();
    }
    /**
     * compares
     * @return
     */
    private boolean equals(){ // Is this == other?
       
        operand1.reduce();
        operand2.reduce();
        if( operand1.num == operand2.num && operand1.den == operand2.den){
            return true;
        }else{
            return false;
        }   
    }
   
    /**
     * takes operation and performs it on operands
     * @return answer in string form;
     */
    public String calculate()
    {
        switch(operation)
        {
        case 0:
        {
            add();
            break;
        }
        case 1:
        {
            subtract();
            break;
        }
        case 2:
        {
            multiply();
            break;
        }
        case 3:
        {
            divide();
            break;
        }
        case 4:
        {
            return ""+equals();
        }
        }
        return operand1.toString();
    }
   
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        RationalCalculator calc = new RationalCalculator();
        System.out.println("Enter an equation of two rational number in format: "n / d operation n /d" Type "q" to quit.");
        calc.getInput();
        do
        {
            System.out.println(""+calc.calculate());
        }while(calc.getInput());
    }
   
    /**
     * Rational Number.
     * This is all a number should know: it's value and how to reduce itself;
     * @author GoldfishGrenade
     *
     */
    class RationalNumber
    {
        private int num; //numerator
        private int den; //denominator
       
        public RationalNumber(int num, int den)
        {
            this.num = num;
            this.den = den;
        }
        public String toString()
        {
            reduce();
            return ""+num+" / "+den;
           
        }
        private void reduce(){
            int yes = 0;
            int smaller;
            int num1=this.num,den1=this.den;
//            you forgot the if num = 0 case
            if(num == 0)
            {
                den = 1;
                return;
            }
            if(num < 0 && den < 0)
            {
                num *= -1;
                den *= -1;
            }
            if(num<0)
            { num1=-1*num;}
            if(den<0)
            { den1=-1*den;}
            if ( num1 < den1 ){
                smaller = num1;
            }else{
                smaller = den1;}

            for ( int div = smaller; div >= 2; div-- ){
                if ( num1 % div == 0 && den1 % div == 0 ){
                    yes = div;
                    break;
                }
            }
            if ( yes != 0 ){
                num /= yes;
                den /= yes;
            }
        }
    }
}


/* I took your methods from your RationalNumber2 class and put them into a RationalCalculator class. When designing an Object Oriented Program, you should first determine which methods and variables are appropriate for each class. The RationalNumber class (is nested) should only contain its numerator, denominator, and very simple operations that it can do on itself (reduction). The other operations (add, subtract, etc.) should be in the RationalCalculator class. This way, you only need one instance of the calculator and pass new operands to it, just like a real calculator. Your old program would have meant that you would have to reinstantiate the entire class every time a new input is given, which wastes space and time. With the RationalNumber class small and lightweight, it is much more efficient.

The main method will loop as long as the input is not 'q'.

if you need the file, send me a message.

P.S. I hope this isn't too advance for the class level you are at, and remember to take out comments that are unnecessary (I added a few to your add and subtract methods)

If your teacher asks you about the Integer.parseInt(), tell him you founding while browsing the Java API. Here's the explanation: Integer is a wrapper class with different methods for manipulating integers. method parseInt(String str) takes a string and converts its numbers into an integer value.

trim() trims a string of the leading and trailing whitespace.

split(regex) splits the string into different parts based on the expression you pass in. Ex:

String ex = "aaabaaababa";
ex.split("b"); // gives you an array of Strings : [aaa, aaa, a, a]

*/