So basically, I'm just trying to return a GCD from two previous numbers,
public static String GCD( int Denominator,int Numerator) {
int newNum=Numerator;
int newDen=Denominator;
int newWhole=Whole;
int GCD=0;
if (Numerator == 0) {
GCD = Denominator;
}
while (Denominator != 0) {
if (Numerator > Denominator) {
Numerator = Numerator - Denominator;
}else {
Denominator = Denominator - Numerator;
}
}
GCD = Denominator;
System.out.println(GCD);
}
You would think that since i declared GCD outside the loop that it would return just fine
but no, i just get 0 as an answer? almost every time..... thoughts?
That's because your while loop is dependent on the value of Denominator as the loop ends when the value of Denominator is decreased to 0.
And right outside the while loop, you're storing the value of Denominator in 'GCD' which is obviously '0'.
So no matter what you do in the while loop, you would get 0 as the final result of your GCD.
I hope this solves your problem.
You need a return statement somewhere in your code. Probably at the end of the method, you need to write return GCD;.
Related
I am struggling with creation of a to calculate fractions and return in an array[3]. So if nominator is 7 and denominator is 3 it should return {2,1,3}, a fraction part and a integer part. If denominator is 0, the integer division should not be executed and I have to return null (not print it). That is what I am struggling with. My code is below:
public class Main{
public static int[] fraction(int nominator, int denominator){
int quota=0;
int numerator=0;
try{
quota = nominator / denominator;
numerator = nominator % denominator;
}
catch(java.lang.ArithmeticException e)
{
if(denominator==0)
{
quota =0;
numerator=0;
}
}
int [] integerArray ={quota, numerator,denominator};
return integerArray;
}
}
As mentioned in the comments, you can just return early once you checked the denominator is 0.
public static int[] fraction(int nominator, int denominator){
if (denominator == 0){
return null
}
int quota = nominator / denominator;
int numerator = nominator % denominator;
int [] integerArray = {quota, numerator,denominator};
return integerArray;
}
you can proceed in 2 different ways:
you can control if denominator is 0 before the try and return null instantly (as said in the comments)
you used try catch so you can return null into the catch block without further controls because you catch an exception
there should not be any compilation errors so if you get one try to read the console and find what's the problem.
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;
}
public class Rational{
public Rational (int numerator, denominator){
if (denominator < 0){
system.out.println("Denominator cannot be negative value. Changing rational to have positive denominator...");
denominator = -denominator;
numerator = -numerator;
}
if (denominator == 0){
system.out.println("Denominator cannot be zero, reinput denominator.");
int n = numerator;
int d = denominator;
}
}
//end of initialization
//behaviors
public Rational inverse(int n, d){
if (numerator == 0){
int temp = numerator;
numerator = denominator;
denominator = temp;
}
else system.out.println("Error, the inverse results in division by zero.");
}
public Rational simplify(int n, d){
if (n%d == 0){
return n;
}
else if (n < d){
return simplify (d, n);
}
else return simplify(d, n%d);
numerator = numerator / n;
denominator = denominator /n;
}
}
New Java student here, and I'm running into an "indentifier expected" error on lines 2, 16, and 24. All those lines are public Rational, and the error points to the closing parentheses specifically. I've tried looking through similar questions on here, but I can't figure out what's wrong with mine. From what I saw the error has to do with defining methods outside of a block, but it looks like it's in one to me. Any help would be appreciated!
There are a couple of problems with your program:
You need to declare the type before each parameter for a function. This is what is causing the error message you are getting For instance, you need:
public Rational inverse(int n, int d){
and
public Rational (int numerator, int denominator){
You need to capitalize s in System.
You need to declare the numerator and denominator fields within the Denominator class. For instance:
public class Rational{
int numerator;
int 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.