So we have to create a Rational class that does the following. Create a project in Java that includes a Rational class. The class represents Rational numbers. It should have only 2 fields num and denom. It should have the following public methods (and any other private methods needed):
- A constructor that takes a num and denom (in that order) as initial field values. If denom is 0, set the number to 0/1.
- An accessor for num (getNum)
- An accessor for denom (getDenom)
- A toString method that returns String of the form "num/denom" (no spaces) where num and denom have the stored values
- An add method that takes a Rational number r and returns a Rational number that is the result of adding r to this Rational number. It should not change this rational number.
- (Extra credit - 2 points) A reduce method with no arguments that reduces this Rational number to lowest form.
I have code that I have done in Intellij IDEA but it will not let me run the program. I know that I am getting errors for most things but I believe it is just because I am not putting something in the correct place or leaving something out. This is what I have so far.
import java.util.Scanner;
public class Rational {
private int num;
private int den; //fields
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("")
public Rational( int n, int d){
num = n;
den = d;
if (d == 0) {
num = 0;
den = 1;
System.out.println("Denominator is 0. Enter a number other than 0 next time.");
}//close if
int g = gcd(num, den);
num = n / g;
den = d / g;
}//close Rational
public String toString() {
if (den == 1) {
return num + "";
} else {
return num + "/" + den;
}
}//close toString
private Rational add(Rational r) {
int newNum = (this.num * r.den) + (r.num * this.den);
int newDen = r.den * this.den;
return new Rational(newNum, newDen);
}//close add
private static int gcd(int m, int n) {
if (0 == n) {
return m;
} else {
return gcd(n, m % n);
}//close else
}//close gcd
}//close main
}//close class