I was assigned to make a rational class by java but I really don't understand what is required as below:
Rational Implement a rational number class: Rational Augment your class with methods for:
Initialization (Constructor): parameters are numerator and
denominator as integers. You must have 3 constructors as follows:
No Parameters: 0 / 1
One Parameter (x): x / 1
Two Parameters (x, y): x / y
float getValue(): returns the value of the number
[bonus] Rational add(Rational r): adds to another rational number
All your numbers should be saved in Reduced Form
Augment your code with a driver class (that contains "main" method)
that constructs two Rational numbers, get the average of the two
numbers and prints it on the screen.
This code implements some of your requirement, but the [bonus] task, and the usage of the reduced form is missing, it is up to you to finish it.
class Rational {
private int nominator;
private int denominator;
public Rational() {
this(0, 1);
}
public Rational(int nominator) {
this(nominator, 1);
}
public Rational(int nominator, int denominator) {
this.nominator = nominator;
this.denominator = denominator;
}
public float getValue() {
return nominator / (float) denominator;
}
}
Related
i was writing Rational class in java to do basic math operation and i want to override methods from
Number class and Comparable interface. i have done that for doubleValue & compareTo methods.
As we know that BigInteger class also extends Number class, so i am confused that which method is being called in doubleValue because i have already override doubleValue & compareTo and calling doubleValue with in doubleValue & compareTo with in compareTo. and it's seems silly too.
import java.math.BigInteger;
class Rational extends Number implements Comparable<Rational>{
// Data fields for numerator and denominator
private BigInteger numerator = BigInteger.ZERO;
private BigInteger denominator = BigInteger.ONE;
// Construct a rational with default properties
Rational(){
numerator = BigInteger.ZERO;
denominator = BigInteger.ONE;
}
Rational(BigInteger numerator,BigInteger denominator){
BigInteger gcde = numerator.gcd(denominator);
BigInteger temp = BigInteger.valueOf( (long)(denominator.compareTo(BigInteger.ZERO)) );
this.numerator = temp.multiply(numerator.divide(gcde));
this.denominator = (denominator.abs()).divide(gcde);
}
// subtract a rational number to this rational a/b - r.a/r.b = a*r.b - r.a*b/r.b*b
public Rational subtract(Rational r){
BigInteger n = (numerator.multiply(r.getDenominator())).subtract(denominator.multiply(r.getNumerator()));
BigInteger d = denominator.multiply(r.getDenominator());
return new Rational(n,d);
}
// Return numerator
public BigInteger getNumerator(){
return numerator;
}
// Return denominator
public BigInteger getDenominator(){
return denominator;
}
#Override // Implement the abstract doubleValue method in Number
public double doubleValue(){
return numerator.doubleValue()/denominator.doubleValue();
}
#Override // Implement the abstract longValue method in Number
public long longValue(){
return (long)doubleValue();
}
#Override
public int compareTo(Rational r){
return (this.subtract(r).getNumerator()).compareTo(BigInteger.ZERO);
}
}
public double doubleValue(){
return numerator.doubleValue()/denominator.doubleValue();
}
numerator is a BigInteger so BigInteger.doubleValue() is being called. Same with denominator. It does not matter that your class also happens to have a doubleValue() function. numerator and denominator are a different class than your Rational class.
Number
/ \
BigInteger Rational
| |
doubleValue doubleValue
Right now, when running my Rational program I get a 1 when creating a new rational with the numerator being 2 and denominator being 0, and my teacher wants me to replace the denominator with a 1 instead of a 0 but I am unable to and get a stack overflow error whenever trying to add an if in the reduce method that is used to reduce the fractions to their simplest form. I have also tried adding an if statement to the constructor where the rational object containing the numerator and denominator are, but still to no avail. I also have a similar problem when a rational is created with a 0 numerator and 2 in the denominator. It is supposed to return 0/1, but 0 is returned. I believe these two are related, does anyone know what's going on here?
public Rational(int numerator, int denominator) {
int gcd = reduce(numerator, denominator);
num = numerator / gcd;
denom = denominator / gcd;
if(denom == 0)
{
denom = 1;
}
}
private static int reduce(int numerator, int denominator) {
if(denominator == 0) numerator = 1;
return reduce(denominator, numerator % denominator);
}
I don't fully understand the quest and cannot speak to the rational portion of your problem but the stack overflow error is caused by your function reduce. The issue is that there is no endpoint for this function and because it is recursive, function calls will build up on the stack until there is no more space available thus resulting in a stack overflow. The following change will fix the stack overflow error.
private static int reduce(int numerator, int denominator) {
if(denominator == 0) { //assuming this is the end point
numerator = 1;
return numerator; //this ends the recursive call
}
return reduce(denominator, numerator % denominator);
}
If you're looking for a method that finds the greatest common denominator then the following change to your function should work.
private static int reduce(int numerator, int denominator) {
if(denominator == 0) {
return numerator;
}
return reduce(denominator, numerator % denominator);
}
I am learning how to code and I am having trouble with my class methods and testing these methods. Here is the problem:
In this lab, we will create a Fraction class. This class is used to represent a ratio of two integers. The main method of the FractionDriver class will contain the code that tests your Fraction class. I recommend that you test your Fraction class incrementally.
Your Fraction class should have two private integer instance variables, numerator and denominator. Initially, the value of numerator should be 0 and the value of denominator should be 1.
Write two mutator methods, setNumerator() and setDenominator(), that allow the user to set the numerator and the denominator to an integer value. Your code should not allow the denominator to be set to 0. If the user tries to set the denominator to 0, the value should not be changed.
Also, include a method named getValue() that returns the value of the numerator divided by the denominator as a double.
Add a toString() method that returns a String representation of the fraction in the form numerator/denominator, for example 5/3.
Finally, add an equals method that determines whether two objects of type Fraction are equal. Note that 3/5 and 6/10 should be considered equal.
Here is my code for my Fraction class:
public class Fraction {
private int numerator = 0;
private int denominator = 1;
private double divide;
//setting numerator and denominator
public void setNumerator(int numerator) {
this.numerator = numerator;
}
public void setDenominator(int denominator) {
if (denominator == 0) {
return;
}
this.denominator = denominator;
}
//returning value of the numerator divided by a denominator as a double
public void getValue() {
divide = numerator / denominator;
this.divide = divide;
System.out.println("The value of this fraction in decimal form is: " + divide);
}
//returning the fraction as a string #/#
public String toString() {
return "Your fraction is: " + numerator + "/" + denominator;
}
public boolean equals(Fraction other) {
if(other.divide == divide) {
return true;
}
return false;
}
}
Here is the code for my driver so far:
public class FractionDriver {
public static void main(String[] args) {
Fraction fract1 = new Fraction();
Fraction fract2 = new Fraction();
//initialize variables
fract1.setNumerator(1);
fract1.setDenominator(2);
fract2.setNumerator(5);
fract2.setDenominator(10);
for(int i = 0; i < 1; i++) {
//testing toString method
System.out.println(fract1.toString());
System.out.println(fract2.toString());
fract1.getValue();
fract2.getValue();
}
}
}
When I test my getValue() method for both fractions, each have the result of 0.0 and I am not sure what I am doing wrong in my class method.
Also, how do I test my equals method?
Dividing an int by an int gives another int. You don't get halves etc.
See Why is the result of 1/3 == 0?
Your method to get value is VOID... so that's your problem.
It should be
//returning value of the numerator divided by a denominator as a double
public double getValue() {
divide = numerator / denominator;
this.divide = divide;
return this.divide;
}
But better to make it
public double getValue() {
return numerator / denominator;
}
So here is my problem. I need help trying to figure out what I'm doing wrong and go from there. I need to create a program that runs these instructions.
Create java class named Fraction. This class is used to represent a ratio of two integers. Include mutator methods that allow the user to set the numerator and the denominator. Also include a method to display the fraction on the screen as a ration (e.g. 5/9). This method does not need to reduce the fraction to lowest terms.
The fraction class should contain the following:
• Private instance variables to store the numerator, denominator, and the ratio_value.
• Constructor(s) that set all of the instance variables.
• Public methods to get and set the instance variables.
• A public method named reduce( ) that returns lowest terms of a fraction.
• A public method named toString( ) that returns a String containing the fraction as a ratio.
• A private method name gcd() that return the greatest common divisor of two integers.
Create a test program that allows the user to create array of 7 fractions. Then the program will sort the fraction in ascending order. The highest and the lowest fractions are thrown away and the remaining fractions are added together. The program should display all the fractions and their sum. The sum should be reduced to lowest terms and displayed on the screen. For example, if the sum is 20/60, the program should display 1/3.
Write a sort method in the test program to sort the array of fractions and calculate the sum.
Assume you have the following 7 fractions: 6/7, 2/4, 3/4, 3/18, 1/8, 10/20, 2/6, then an example of the output after throwing away the lowest and the largest fractions, will be:
3 / 18 + 2 / 6 + 2 / 4 + 10 / 20 + 3 / 4 = 9 / 4
I completely lost on how to solve this and stuck where I am at. Below is a copy of my class and .main file. I have some different things that I have tried commented out with '//' so sorry for the long codes in advance. I've tried over and over to figure this and have been stuck for days. It keeps giving me this weird error called null.
How can I get this to work? Thanks.
import java.io.*;
import java.util.*;
public class Arrays_hw5 {
private static final Scanner keyb = null;
public static void main(String[] args) {
Fraction [] fr = new Fraction[7];
String reduce = "";
int numerator = 0, denominator = 0;
Scanner keyb = null;
FileInputStream fis = null;
//Scanner keyb = new Scanner(System.in);
try {
fis = new FileInputStream(new File("Fraction"));
keyb = new Scanner(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();}
for (int i = 0; i < fr.length; i++) {
//System.out.println("Enter numerator then denominator, hit enter after each entry: ");
// fr[i] = new Fraction(i, i);
// fr[i].getNumerator(keyb.nextInt());
// fr[i].denominator(keyb.nextInt());
System.out.print(fr[i] + " "); }}
public static void selectionSort(int[]arr)
{
int smallest = 0;
for (int outer = 0; outer < arr.length - 1; outer++)
{
smallest = outer;
for(int inner = outer + 1; inner < arr.length; inner++)
{
if (arr[inner] < arr[smallest])
smallest = inner;
}
int v = arr[outer];
arr[outer] = arr[smallest];
arr[smallest] = v; }
}
}
Here is the Fraction Class.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Fraction {
public int numerator = 1;
public int denominator = 1;
public int gcd;
public Fraction() {
super();
}
public Fraction(int n, int d) {
numerator = n;
denominator = d;
}
public int getNumerator() {
return numerator;
}
public void setNumerator(int numerator) {
this.numerator = numerator;
}
public int getDenominator() {
return denominator;
}
public void setDenominator(int denominator) {
this.denominator = denominator;
}
private static int gcd(int numerator, int denominator) {
return denominator == 0 ? numerator : gcd(denominator, numerator % denominator);
}
public double decimal(double numerator, double denominator) {
return numerator / denominator;
}
public static String reduce(int numerator, int denominator) {
int gcd = gcd(numerator, denominator);
return (numerator / gcd) + "/" + (denominator / gcd);
}
#Override
public String toString() {
return numerator + "/" + denominator;
}}
Prepare yourself for a long answer. First it is always best to plan out a project before doing any code so here are the steps we will take: 1) Read input from user and store this input into an array of Fractions. 2) Sort this Fraction array then remove (ignore) highest and lowest values in array. 3) Sum all values of array excluding highest and lowest values, reduce this sum, and print this sum to the screen.
Step 1) Read User Input
You are on the right track but you do not read the user input properly. First, you for some reason open a file. This is unnecessary as you only need to read from the command line. Second, you do not read nor store the input properly. I would suggest repeatedly prompting the user to input a numerator then a denominator. And for every time you read one numerator and one denominator, store these values as a Fraction before you re-prompt the user for input. See the following code block to understand what I mean:
Fraction[7] fractions = new Fraction[7]; // array that will hold our fractions
Scanner inputScanner = new Scanner(System.in); // scanner that takes input from the command line
...
public void readInput()
{
int tempNumer; // variable to store numerator on each iteration
int tempDenom; // variable to store denominator on each iteration
for (int i = 0; i < fractions.length; i++)
{
System.out.println("Enter a numerator:");
tempNumer = inputScanner.nexInt(); // store the user-inputted numerator
System.out.println("Enter a denominator");
tempDenom = inputScanner.nextInt(); // store the user-inputted denominator
fractions[i] = new Fraction(tempNumer, tempDenom); // store a Fraction from our temp variables into our fractions array
}
return;
}
Upon completion of this method, the fractions array will be full of Fraction objects in the order that the user inputted.
Step 2) Sort the fractions array
So, how do we know if a fraction, in normal math, is larger than another fractions? Well, we convert both fractions to have the gcd as each individual fraction's denominator, then we compare the numerators (btw, your gcd method is so wrong. The gcd is between two fraction's denominators, NOT the numerator and denominator of one fraction). The larger numerator at this point is the larger fractions. So, it would be easiest to have a method called fracCompare that takes in two fractions, converts both of them, then return which fraction is larger. We can do this as follows:
public int fracCompare(Fraction fracOne, Fraction fracTwo)
{
// First, find the gcd of the fractions
int gcd = gcd(fracOne.getDenominator, fracTwo.getDenominator);
// Now, we need to convert the numerator accordingly
// We will do this by finding the factor by which the denominator is
// increased and multiply the numerator by this factor
int factorOne = gcd / fracOne.getDenominator();
int tempFracOneNum = fracOne.getNumerator() * factorOne;
int factorTwo = gcd / fracTwo.getDenominator();
int tempFracTwoNum = fracTwo.getNumerator() * factorTwo;
// Now we compare these numerators
// We will return 1 if fracOne is greater than fracTwo
// We will return 2 if fracTwo is greater than fracOne
// We will return 0 if they are the same
if (tempFracOneNum > tempFracTwoNum)
return 1;
else if (tempFracTwoNum > tempFracOneNum)
return 2;
else
return 0;
}
public int gcd(int firstNum, int secondNum)
{
int a = firstNum.getDenominator();
int b = secondNum.getDenominator();
while(a != 0 && b != 0) // until either one of them is 0
{
int c = b;
b = a % b;
a = c;
}
return a+b; // either one is 0, so return the non-zero value
}
A note: I blatantly stole this gcd method from The user, Rushil's answer on another post. Now that we have a compare method, we can sort the array. I will leave the sorting to you because I'm getting sick of formatting code but here is some bubble sort pseudocode to get you started:
i = 0
loop until i = fractions.length - 1
j = i
loop until j = fractions.length - 1
if fraction at j > fraction at j+1
swap fraction at j and fraction at j+1
Step 3) Sum all Fractions in fractions array
Finally at the last step. In order to add fractions we again need to use the gcd. We use this gdc to see what to increase the numerator of both adding fractions by. We will then take this sum and add it to all the other values in the array. Finally, we will reduce the large sum.
int tempGcd;
int tempFactorOne;
int tempFactorTwo;
Fraction sum = fractions[1];
for (int i = 2; i < fractions.length - 2; i++) // we loop from 2 to fractions.length-2 because
// we ignore the least and greatest values in the array
// and we assigned the initial sum to the first fraction
{
tempGcd = gcd(sum.getDenominator(), fractions[i].getDenominator());
tempFactorOne = tempGcd / sum.getDenominator();
tempFactorTwo = tempGcd / fractions[i].getDenominator();
sum.setNumerator(tempFactorOne * sum.getNumerator() + tempFactorTwo * fractions[i].getNumerator()); // add the numerators and store as the sum
sum.setDenominator(gcd); // obviously the denominator is the gcd
}
Hopefully this all should work. I'm sick of typing so I'll leave the reducing of the fraction to you. It is pretty simple--you just need to find the greatest common divisor of the numerator and denominator and then divide both by that divisor. Sorry if my exact code doesn't compile, I'm too lazy to do it myself and you shouldn't be plagiarizing for a school project anyway.
Rational numbers contain an integer numerator and denominator. Write the code to implement a class named Rational which stores two private ints (numer and denom) with the following methods:
public Rational(int,int)
constructor that sets the numer and denom
public Rational(Rational)
//copy constructor for a Rational object
public void setNumer(int)
//sets the numerator to the paramter value
public int getNumer()
//returns the stored numerator
public void setDenom(int)
//sets the denominator to the paramter value
public int getDenom() //returns the stored denominator
//return a new Rational object that contains the reciprocal of the object that invokes the method.
public Rational reciprocal()
//returns a new Rational object that contains the product of the two paramteres.
public static Rational multiply(Rational a, Rational b)
I am stuck at the 7th method for this class. I don't understand how to flip the numbers so that they are reciprocals. Any help will be greatly Appreciated. This is my code so far:
class Rational {
private int numer;
private int denom;
public Rational(int numer, int denom){
this.numer = numer;
this.denom = denom;
}
public Rational(Rational rational){
rational = new Rational(numer, denom);
}
public void setNumber(int fum){
numer = fum;
}
public int getNumber(){
return 5;
}
public void setDenom(int Dum){
denom = Dum;
}
public int getDenom(){
return 10;
}
public Rational reciprocal(){
;
}
}
public class Results {
public static void main(String[] args){
}
}
Math is Fun: Reciprocal of a Fraction says (in part) to get the reciprocal of a fraction, just turn it upside down.
public Rational reciprocal(){
return new Rational(this.denom, this.number);
}
You have to return a new Rational with the numbers fliped.
public Rational reciprocal(){
return new Rational(this.denom,this.numer);
}
Try this:
public Rational reciprocal(){
return new Rational(denom, numer);
}
It get the reciprocal which is just the numerator and denominator flipped. return new Rational(denom, numer); does this by creating a new rational instance with the denominator from the current one as the numerator and as the numerator as the current instance as the denominator.
Really a reciprocal is one divided by the original number as said here, but flipping the numerator and denominator does the same thing as dividing by its self.