For this project I have to create a rational number class that has 2 parts an int numerator and int denominator. I had to add two contractions where the negative denominator has to be moved to the numerator. I also added getters and setters and a toString(). The data should print as numerator/denominator.
I also had to code member methods for addition, subtraction, multiplications, and division and negate(?) I am not sure what that last part means.
I have the class done already but Eclipse is giving me an error with the add and subtract method around the part where I typed "temp". Please let me know if I have anything that is incorrect or if I am missing something.
public class Rational {
private int numerator;
private int denominator;
public Rational()
{
numerator = 0;
denominator = 1;
}
public Rational(int n, int d, int num, int denom)
{
if (d < 0)
{
num = -n;
denom = d;
}
else if (d == 0)
{
num = n;
denom = 1;
}
else
{
num = n;
denom = 0;
}
}
public int getNumerator()
{
return numerator;
}
public int getDenominator()
{
return denominator;
}
public void setNumerator(int n)
{
numerator = n;
}
public void setDenominator(int n, int d, int num, int denom)
{
denominator = d;
if (d < 0)
{
num = -n;
denom = d;
}
else if (d == 0)
{
num = n;
denom = 1;
}
else
{
num = n;
denom = 0;
}
}
public String toString()
{
return numerator + "/" + denominator;
}
public boolean equals (Rational other)
{
if(numerator * other.denominator == denominator * other.numerator)
return true;
else
return false;
}
public boolean notequals(Rational other)
{
if (numerator * other.denominator != denominator * other.numerator)
return true;
else
return false;
}
//subtract method
public Rational subtract(Rational other)
{
Rational temp;
temp.numerator = numerator * other.denominator - denominator * other.numerator;
temp.denominator = denominator * other.denominator;
return temp;
}
//add method
public Rational add(Rational other)
{
Rational temp;
temp.numerator = numerator * other.denominator + denominator * other.numerator;
temp.denominator = denominator * other.denominator;
return temp;
}
public boolean lessThan(Rational other)
{
return(numerator * other.denominator < denominator * other.numerator);
}
public boolean greterThan(Rational other)
{
return(numerator * other.denominator > denominator * other.numerator);
}
public boolean lessThanEqualTo(Rational other)
{
return(numerator * other.denominator <= denominator * other.numerator);
}
public boolean greaterThanEqual(Rational other)
{
return(numerator * other.denominator >= denominator * other.numerator);
}
}
I am however struggling with the main to test each method.
Here is what I have so far:
public class Project4 {
public static void main(String[] args) {
Rational a = new Rational();
Rational b = new Rational();
Rational c;
c = a.add(b);
}
}
//Here goes commented code:
public class Rational
{
private int numerator; // You can declare private variables here all right
private int denominator;
// This constructor creates a new object of the class Rational. Objects are instances of that class, all right?
public Rational()
{
numerator = 0;
denominator = 1;
//private int numerator = 0;
//private int denominator = 1; // I get it, you need them even when not giving arguments, but it is better to do stuff in constructors. You better try to make declarations in the constructor and not in the begining of a class, if possible.
}
// Here is the constructor overriden, so you can create an instance that contains 4 arguments. (n,d,num,denom) Good.
public Rational(int n, int d, int num, int denom)
{
// You repeat yourself in the constructor.
// public void setDenominator(int n, int d, int num, int denom) does the same thing right?
// I don't remember now, but I think that on instantiation you can't use methods, if you don't add the word static.
// public static void setDenominator(int n, int d, int num, int denom) will make you able to call it in the constructor!
if (d < 0)
{
num = -n;
denom = d;
}
else if (d == 0)
{
num = n;
denom = 1;
}
else
{
num = n;
denom = 0;
}
}
public int getNumerator()
{
return numerator;
}
public int getDenominator()
{
return denominator;
}
public void setNumerator(int n)
{
numerator = n;
}
public void setDenominator(int n, int d, int num, int denom) // FIX IT. ADD STATIC
{
denominator = d;
if (d < 0)
{
num = -n;
denom = d;
}
else if (d == 0)
{
num = n;
denom = 1;
}
else
{
num = n;
denom = 0;
}
}
public String toString()
{
return numerator + "/" + denominator;
}
public boolean equals (Rational other)
{
if(numerator * other.denominator == denominator * other.numerator)
return true;
else
return false;
}
public boolean notequals(Rational other)
{
if (numerator * other.denominator != denominator * other.numerator)
return true;
else
return false;
}
//subtract method
public Rational subtract(Rational other)
{
Rational temp;
temp.numerator = numerator * other.denominator - denominator * other.numerator;
temp.denominator = denominator * other.denominator;
return temp;
} // THIS RETURNS temp THAT IS AN OBJECT OF THE TYPE Rational!!! Remember that.
//add method
public Rational add(Rational other)
{
Rational temp;
temp.numerator = numerator * other.denominator + denominator * other.numerator;
temp.denominator = denominator * other.denominator;
return temp;
}// THIS RETURNS temp THAT IS AN OBJECT OF THE TYPE Rational!!! Remember that.
public boolean lessThan(Rational other)
{
return(numerator * other.denominator < denominator * other.numerator);
}// What type is this method return? Here is the gap you must fill. If you learn how to handel what methods return, you will be fine. Try stuff out.
public boolean greterThan(Rational other)
{
return(numerator * other.denominator > denominator * other.numerator);
}
public boolean lessThanEqualTo(Rational other)
{
return(numerator * other.denominator <= denominator * other.numerator);
}
public boolean greaterThanEqual(Rational other)
{
return(numerator * other.denominator >= denominator * other.numerator);
}
}
Related
How can i Generate an array with 10 random fractions between 10/1 and 1/10 . i have coded java class Rational to do this work .
inside Rational Class , there are some basic methods are defined . please have a look on the class .
public class Rational {
// Private instance variables
private int numerator;
private int denominator;
// Constructor
public Rational(){
this.numerator = 0;
this.denominator = 1;
}
// Overloaded constructor
public Rational(int num, int den){
this.numerator = num;
this.denominator = den;
reduce();
}
// Getter method for numerator
public int getNumerator(){
return this.numerator;
}
// Getter method for denominator
public int getDenominator(){
return this.denominator;
}
// Getter method for double
public double toDouble(){
return(double)this.numerator/this.denominator;
}
// Getter method for string
public String toString(){
if(denominator == 0){
return "ERROR";
}
if(denominator == 1){
return this.numerator + "";
}
else {
return this.numerator + "/" + this.denominator;
}
}
// Void method for negate
public void negate(){
this.numerator = -1 * numerator;
}
// Void method for invert
public void invert(){
int flip = this.numerator;
this.numerator = this.denominator;
this.denominator = flip;
}
// Value method for addition
public Rational add(Rational test){
this.numerator = (numerator * denominator) + (test.getDenominator() * test.getNumerator());
this.denominator = test.getDenominator() * denominator;
return new Rational(numerator,denominator);
}
// Euclid's GCD
private static int gcd(int x, int y){
if (0 == y){
return x;
}
else {
return gcd(y,x%y);
}
}
// Void method for reduce, using GCD
public void reduce(){
int div;
div = Rational.gcd(numerator, denominator);
this.numerator = numerator/div;
this.denominator = denominator/div;
}
// *Bonus* value method for multiplication
public Rational multiply(Rational test){
int numx = this.numerator * test.getNumerator();
int denx = this.denominator * test.getDenominator();
return new Rational(numx, denx);
}
}
But i am having problem in creating that logic to generate random fraction with that specific range ...
You can follow this simple strategy. You know that your fraction is between 1/10 and 10, which means,
1/10 < num/den < 10 ...(1)
Which implies that,
den/10 < num < 10*den ...(2)
So, first randomly fix the den (choose randomly from 0 to 9). Once you have fixed this, randomly choose a number from the range den/10 to 10*den
Please explain how to implement main method. i am having trouble with the main method and the line after main method, why the line after main method showing illegal start of expression?? is it because i forgot to put bracket somewhere or my code is wrong?? the code is suppose to perform arithmetic with fraction.
public class Rational{
public static void main(String [] args){
public int numerator;
public int denominator;
public Rational(int numerator, int denominator)
{
this.numerator = numerator;
this.denominator = denominator;
reduce();
}
public Rational add(Rational other)
{
int num = numerator * other.denominator + other.numerator * denominator;
int den = denominator * other.denominator;
return new Rational(num, den);
}
public Rational subtract(Rational other)
{
int num = numerator * other.denominator - other.numerator * denominator;
int den = denominator * other.denominator;
return new Rational(num, den);
}
public Rational multiply(Rational other)
{
int num = numerator * other.numerator;
int den = denominator * other.denominator;
return new Rational(num, den);
}
public Rational divide(Rational other)
{
int num = numerator * other.denominator;
int den = denominator * other.numerator;
return new Rational(num, den);
}
private void reduce()
{
int min = 0;
if(numerator > denominator)
{
min = denominator;
}
else
{
min = numerator;
}
for(int i = min; i > 1; i--)
{
boolean isNumDiv = numerator % i == 0;
boolean isDenDiv = denominator % i == 0;
if(isNumDiv && isDenDiv)
{
numerator = numerator / i;
denominator = denominator / i;
break;
}
}
}
public String toString()
{
return numerator + " / " + denominator;
}
} }
Suppose you have to create a program that prints a sum. You can create a file Sum.java with the Sum class inside it. Like this:
public class Sum {
public int x;
public int y;
public Sum(int x, int y) {
this.x = x;
this.y = y;
}
public int sumMyNumbers() {
return x + y;
}
}
Now you can create a file named Main.java with your Main class that will be the entry point of your program and it could be like this:
public class Main {
public static void main(String[] args) {
// It will print the number 4 on your console
System.out.println(new Sum(2, 2).sumMyNumbers());
// Or like this:
Sum mySum = new Sum(2,2);
System.out.println(mySum.sumMyNumbers());
// Or even like this:
int i = new Sum(2, 2).sumMyNumbers();
System.out.println(i);
}
}
So your first mistake is that you are putting everything inside your main method.
so I am trying to build this ADT for rational numbers in java but for some reason I keep getting this error that says cannot find symbol when trying to compile. What em I doing wrong? Is this error because of my syntax?
Author: Juan Suarez
// Class : CS1102 ~ java
// Date : 01/30/2018
// Topic : This porblem set focuse on the implemantation of an
// ADT for rational numbers.
public class RationalC implements Rational {
private int num;
private int den;
// ****************** CONSTRUCTOR **********************************
public RationalC (int numerator, int denominator) {
if (this.den == 0){
throw new ArithmeticException("*** WARNING! input non zero denominator");
}
int reduceFraction = gcd(numerator, denominator);
this.num = numerator / reduceFraction;
this.den = denominator / reduceFraction;
if (this.den < 0) {
this.den = this.den * -1;
this.num = this.num * -1;
}
}
//********************* GETTERS ************************************
public int getNumerator() { return this.num; }
public int getDenominator() { return this.den; }
public boolean equal(Rational b) {
boolean
a = this.getNumerator == b.getNumerator;
v = this.getDenominator == b.getDenominator;
return a && v;
}
// ******************* OPERATIONS **********************************
//return this + that
//
public RationalC plus(Rational b) {
int commonDenominator = this.getDenominator() * b.getDenominator();
int num1 = b.getDenominator() * this.getNumerator();
int num2 = b.getNumerator() * this.getDenominator();
int complete = num1 + num2;
return new RationalC (complete, commonDenominator);
}
//returns this - that
//
public RationalC subtract(Rational b) {
int commonDenominator = this.getDenominator() * b.getDenominator();
int num1 = b.getDenominator() * this.getNumerator();
int num2 = b.getNumerator() * this.getDenominator();
int complete = num1 - num2;
return new RationalC (complete, commonDenominator);
}
// return this * that
//
public Rational multiply(Rational b){
int top = this.getNumerator() * b.getNumerator();
int bottom = this.getDenominator() * b.getDenominator();
return new RationalC (top, bottom);
}
//return this / that
//
public Rational divide(Rational b){
int top = this.getNumerator() * b.getDenominator();
int bottom = this.getDenominator() * b.getNumerator();
return new RationalC (top, bottom);
}
//retuns value
//
public boolean equals(Rational b) {
if (num == b.getNumerator() && this.getDenominator() == b.getDenominator() )
return(true);
}
//********************* TOOLS **************************************
//returns the rational number to a string
//
public String toString() {
return "(" + this.num + "," + this.den + ")";
}
//returns -1 , 0, +1 if the value of the rational is <, >, or =
//
public int compareTo(Rational b) {
long leftHand = this.getNumerator() * b.getDenominator();
long rightHand = this.getDenominator() * b.getNumerator();
if (leftHand < rightHand) return -1;
if (leftHand > rightHand) return +1;
return 0;
}
private static int gcd(int m, int n) {
if(m < 0) m = -m;
if(n < 0) n = -n;
return m * (n / gcd(m,n));
}
public Rational reciprical(Rational b){
return new RationalC (this.getDenominator(), this.getNumerator() );
}
//******************* TEST UNIT ************************************
public static void main(String[] args) {
x = new Rational (1,2);
y = new Rational (1,3);
z = x.plus(y);
StdOut.println(z);
}
}
In the below piece of code, you didn't declare local variable v.
public boolean equal(Rational b) {
boolean
a = this.getNumerator == b.getNumerator;
v = this.getDenominator == b.getDenominator;
return a && v;
}
getNumerator and getDenominator are methods.
Call them as this.getNumerator() and this.getDenominator().
Also make sure Rational class is having getNumerator and getDenominator methods.
I have to sort an array of fractions here is my code for the class which is working fine.
public class Fraction implements Comparable<Fraction>{
private int numerator;
private int denominator;
public Fraction(int num, int den){
numerator = num;
denominator = den;
}
public int compareTo(Fraction fraction){
if(decimalValue()>fraction.decimalValue()){
return 1;
}else if(decimalValue()<fraction.decimalValue()){
return -1;
}else{
return 0;
}
}
public Fraction reduce(int numerator, int denominator){
if(numerator==0&&denominator==0){
numerator = 0;
denominator = 0;
}
else{
for(int x = Math.min(Math.abs(numerator), Math.abs(denominator)); x>0; x--){
if(denominator == numerator){
numerator = 1;
denominator = 1;
}
else if(numerator == 0){
numerator = 0;
denominator = 1;
}
else if(numerator%x==0 && denominator%x==0){
numerator = numerator/x;
denominator = denominator/x;
}
}
}
public double decimalValue(){
double decimal = (numerator*1.0)/(1.0*denominator);
return decimal;
}
public String toString(){
reduce(numerator, denominator);
return ((numerator) + "/" + (denominator));
}
}
For some reason the sort() is not working if I used it with a comparator like in the answer it works but I don't understand why this doesn't work. Here is the tester:
public class FractionChecker{
public static void main (String[]args){
int n, d;
Random rand = new Random();
Fraction[] f = new Fraction [20];
for (int j= 0; j<20; j++){
n = rand.nextInt(20);
d = rand.nextInt(19)+1;
f[j] = new Fraction (n,d);
}
System.out.println("Unsorted " + Arrays.toString(f));
Arrays.sort(f);
}
}
Error:
----jGRASP exec: java FractionChecker
Unsorted [7/6, 15/14, 5/15, 8/9, 19/16, 16/5, 11/16, 2/9, 11/10, 10/12, 12/11, 9/18, 15/4, 11/4, 10/7, 12/8, 13/14, 19/5, 19/15, 13/5]
Exception in thread "main" java.lang.ClassCastException: Fraction cannot be cast to java.lang.Comparable
at java.util.Arrays.mergeSort(Arrays.java:1144)
at java.util.Arrays.mergeSort(Arrays.java:1155)
at java.util.Arrays.mergeSort(Arrays.java:1155)
at java.util.Arrays.sort(Arrays.java:1079)
at FractionChecker.main(FractionChecker.java:18)
----jGRASP wedge: exit code for process is 1.
----jGRASP: operation complete.
This is the error I am getting when I use Arrays.sort(f) and I am not sure why.
Collections.sort expects a List whose type implements Comparable. You're providing an array of Fraction objects instead.
You should use Arrays.sort instead:
Arrays.sort(f);
If the above throws a ClassCastException for some reason, you can try this version of Arrays.sort, which requires a Comparator as an argument that will do the comparing:
Arrays.sort(f, new java.util.Comparator<Fraction>() {
#Override
public int compare(Fraction f1, Fraction f2) {
return f1.compareTo(f2);
}
});
I don't see your decimalValue code. A better way to compare fractions in any case may be:
long left = numerator * other.denominator;
long right = other.numerator * denominator;
if (left == right) {
return 0;
} else if (left < right) {
return -1;
} else /* if (left > right) */ {
return 1;
}
Not that this will increase your performance drastically but it is just neater and handles division by zero in a sensible way.
The code below works and prints success
import java.util.Arrays;
public class Fraction implements Comparable<Fraction>{
private int numerator;
private int denominator;
public Fraction(int num, int den){
numerator = num;
denominator = den;
}
public int compareTo(Fraction fraction){
if(decimalValue()>fraction.decimalValue()){
return 1;
}else if(decimalValue()<fraction.decimalValue()){
return -1;
}else{
return 0;
}
}
public double decimalValue(){
double decimal = (numerator*1.0)/(1.0*denominator);
return decimal;
}
public String toString(){
return ((numerator) + "/" + (denominator));
}
public static void main(String[] a) {
Fraction[] fractions = new Fraction[2];
fractions[0] = new Fraction(1,1);
fractions[1] = new Fraction(2,3);
Arrays.sort(fractions);
System.out.println("success");
}
}
My final result when testing these classes returns zero/zero, but it should return an actual answer.
Here is a small sample of the code.
parent class:
http://pastebin.com/QvxqgrfN
subclass: (here lies the problem - by the way, the main section is for testing results. I will take it out afterwards.)
public class HW6Fraction extends Fraction {
public HW6Fraction(int num, int denom) {
super();
}
public Fraction add(Fraction f) { // Add method
int num = getNumerator() + f.getNumerator();
int denom = getDenominator() + f.getDenominator();
Fraction result = new Fraction(num, denom);
return result;
}
public static void main(String[] args) {
HW6Fraction F1 = new HW6Fraction(4, 7);
HW6Fraction F2 = new HW6Fraction(1, 3);
Fraction F3 = F1.add(F2);
System.out.println("sum=" + F3.getNumerator() + "/" + F3.getDenominator());
}
}
Parent Class
public class Fraction {
private int numerator; //Numerator of fraction
private int denominator; //Denominator of fraction
public Fraction(int num, int denom) { //Constructor
numerator = num;
denominator = denom;
}
public Fraction() { //Constructor w/ no parameters
new Fraction(0, 1);
}
public Fraction(int num) { //Constructor w/ numerator parameter
numerator = num;
int denom = 1;
}
public int getNumerator() { //getNumerator method
return numerator;
}
public int getDenominator() { //getDenominator method
return denominator;
}
public void setNumerator(int num) { //setNumerator method
numerator = num;
}
public void setDenominator(int denom) { //setDenominator method
denominator = denom;
}
public Fraction add(Fraction f) { //Add method
int num = numerator * f.getDenominator() + f.getNumerator() *
denominator;
int denom = denominator * f.getDenominator();
Fraction result = new Fraction(num, denom);
return result;
}
public Fraction subtract(Fraction f) { //Subtract method
int num = numerator * f.getDenominator() - f.getNumerator() *
denominator;
int denom = denominator * f.getDenominator();
Fraction result = new Fraction(num, denom);
return result;
}
public Fraction multiply(Fraction f) { //Multiply method
int num = numerator * f.getNumerator();
int denom = denominator * f.getDenominator();
Fraction result = new Fraction(num, denom);
return result;
}
public Fraction divide(Fraction f) { //Divide method
int num = numerator * f.getDenominator();
int denom = denominator * f.getNumerator();
Fraction result = new Fraction(num, denom);
return result;
}
}
You are not passing arguments to super constructor:
public HW6Fraction(int num, int denom){
super();
}
should be:
public HW6Fraction(int num, int denom){
super(num, denom);
}
otherwise the parent class won't initialize instance variables (they'll be 0 indeed).