public class Rational {
int num, denom; /*I'm building an object named "Rational, which takes in two int values, num and denom, and represent them as a rational number(num/denom)*/
public Rational(int a, int b){//this is the constructor
this.num = a;
this.denom = b;
}
public Rational(){//this is just another form of constructor
this.num = 0;
this.denum = 0;
}
public static void printRational(Rational x){/*this is the method that prints the rational number in a fractional format*/
System.out.println(x.num+"/"+x.denom);
}
public static int gcd(int a, int b){/*this is the method which finds the greatest common denominator of numerator of denominator. This will be used to simplify the fraction*/
if(b == 0){
return a;
}
else{
return gcd(b, a%b);
}
}
public static Rational add(Rational x, Rational y){/*this is a method which adds the two rational numbers(or objects) together, then simplify it utilizing the gcd method*/
Rational z = new Rational();
z.denom = (x.denom * y.denom);
z.num = y.num*x.denom + x.num*y.denom;
z.denom = z.denom/gcd(z.num, z.denom);
z.num = z.num/gcd(z.num, z.denom);
return z;
}
public static void main(String[] args) {
Rational y = new Rational(1, 2); //1st Rational Object: y
Rational z = new Rational(2, 6); //2nd Rational Object: z
printRational(add(y, z)); //implementing the method
//result? so far so good. I get the correct result
}
}
The problem I'm facing is I don't understand is that why this won't work instead and give me an error.
public static Rational add(Rational x, Rational y){
Rational z = new Rational();
int a = (x.denom * y.denom);
int b = y.num*x.denom + x.num*y.denom;
z.denom = a/gcd(z.num, z.denom);
z.num = b/gcd(z.num, z.denom);
return z;
}
Why would this give me an error message: "Exception in thread "main" java.lang.ArithmeticException: / by zero
at Rational.add(Rational.java:47)
at Rational.main(Rational.java:58)" when the instances of the object are int types and I'm temporarility storing the value into int a, b; Help me please if you see something I don't see!! Thank you.
I do not know what is the exact problem, when you say "It is not working". It would have been helpful if you could tell what error is it giving. However, from what you have said, Could it be because you have not initialized z.num and z.denom and are sending them to gcd() ?? They will both be zero, as they are primitive data type "int" so your gcd method will return 0 and cause an exception.
public static Rational add(Rational x, Rational y){
Rational z = new Rational();
int a = (x.denom * y.denom);
int b = y.num*x.denom + x.num*y.denom;
z.denom = a/gcd(z.num, z.denom); <--------------
z.num = b/gcd(z.num, z.denom); <--------------
return z;
}
You are using the wrong implementation for dividing with gcd as the number changes in this case.
z.denom = z.denom/gcd(z.num, z.denom);
z.num = z.num/gcd(z.num, z.denom);//z.denom is changed here.
The z.denom can be 0 as it is changed so gcd is 0 and hence the exception.
So what you can do is.
int gcd = gcd(z.num, z.denom);
z.denom /= gcd;
z.num /= gcd;
Also this fails when either of num or denom is a 0.
Related
I'm trying to use Junit for the first time but I'm facing some unexpected failure.
Here is the failure message:
org.opentest4j.AssertionFailedError: expected: <2> but was: <19>.
It would be great if someone will be able to help me understand where is my error.
I spend more than 30 minutes in trying to understand the reason behind it and I can't. I guess I need to do a minor change somewhere.
public class Fraction {
private int numerator;
private int denominator;
public int getNumerator() {
return numerator;
}
public int getDenomonator() {
return denominator;
}
public Fraction(int n, int d) {
numerator = n;
denominator = d;
}
/**
* This method is adding other fraction
* to our current(this) fraction
* #param otherFraction
*/
public void add(Fraction otherFraction) {
int a = numerator;
int b = denominator;
int c = otherFraction.getNumerator();
int d = otherFraction.getDenomonator();
numerator = a * d + b * c;
denominator = b * d;
int min = denominator;
if (numerator < denominator) {
min = numerator;
}
int commonDiv = 1;
for (int i = 1; i <= min; i++) {
if ((numerator % i == 0) && (denominator % 1 == 0)) {
commonDiv = i;
}
}
numerator = numerator / commonDiv;
denominator = denominator / commonDiv;
if (numerator == 0) denominator = 1;
}
}
Test:
class FreactionTest {
#Test
void test() {
Fraction f1 = new Fraction(3,4);
Fraction f2 = new Fraction(5,6);
f1.add(f2);
assertEquals(f1.getNumerator(),19);
assertEquals(f1.getDenomonator(),12);
}
#Test
void testAddNegative() {
Fraction f1 = new Fraction(3,4);
Fraction f2 = new Fraction(-3,4);
f1.add(f2);
assertEquals(f1.getNumerator(),0);
assertEquals(f1.getDenomonator(),1);
}
}
I expected the code to run successfully.
It looks like you have your expected/actual backwards in the call to assertEquals(). According to the docs here, the first argument is the expected value, and the second argument is the actual value. So you need to switch your arguments, since right now you're hard-coding the actual result to be 19. The call you're trying to test should be the second argument, and the value you expect to be returned should be the first argument. You're doing it in all your other assertEquals() calls also, so be sure to change those as well.
what is the best method of calculating the product of integer variables through method parameters? I have tried using mathematical symbols such as '*' to get a result but nothing has been successful and I am lost for answers. Any advice would be greatly appreciated, thanks in advance.
int productOfThreeNumbers(int number1, int number2, int number3){
productOfThreeNumbers(number1 * number2 * number3);
return 0;
}
If you wish to obtain an integer value from a multiplication of integers you could try
public Integer mult(int a,int b){
int c = a*b;
return c;
}
If you want to obtain a double value you could use:
public double mult(int a,int b){
double n1 = (double) a;
double n2 = (double) b;
double c = n1*n2;
return c;
}
you call the method with:
int a = 1;
int b = 2;
int c = mult(a,b);
or
int a = 1;
int b = 2;
double c = mult(a,b);
depending on which method you are using.
But looking at your code just do:
int productOfThreeNumbers(int number1, int number2, int number3){
return (number1 * number2 * number3);
}
Define TriFunction
#FunctionalInterface
interface TriFunction<A,B,C,R> {
R apply(A a, B b, C c);
}
Then, use it:
public class Main {
public static void main(String[] args) {
TriFunction<Integer, Integer, Integer, Integer> triMult = (x,y,z) -> x*y*z;
System.out.println(triMult.apply(2, 1, 3));
}
}
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;
The purpose of this code is to calculate (1/2+3/4+...+99/100)^2. But my loop can't be executed correctly.
The result of r1 is 3/4 instead of 99/100, what's wrong with my code?
I think my loop can be run because the y I can get it correctly.
So how can i correct my code and make it able to calculate (1/2+3/4+...+99/100)^2 ? Thank you for answering.
import java.math.BigInteger;
public class Rational {
// Data fields for numerator and denominator
private BigInteger numerator = BigInteger.ZERO;
private BigInteger denominator = BigInteger.ONE;
/** Construct a rational with default properties */
public Rational() {
this(BigInteger.ZERO, BigInteger.ONE);
}
/** Construct a rational with specified numerator and denominator */
public Rational(BigInteger numerator, BigInteger denominator) {
BigInteger gcd=new BigInteger(String.valueOf(gcd(numerator,
denominator)));
BigInteger r1=new
BigInteger(String.valueOf(denominator.compareTo(BigInteger.ZERO)));
this.numerator = (r1.multiply(numerator)).divide(gcd);
this.denominator = (denominator.abs()).divide(gcd);
}
/** Find GCD of two numbers */
private static long gcd(BigInteger n, BigInteger d) {
BigInteger n1 = n.abs();
BigInteger n2 = d.abs();
int gcd = 1;
for (int k = 1; (new BigInteger(String.valueOf(k))).compareTo(n1)<=0 &&
(new BigInteger(String.valueOf(k))).compareTo(n2)<=0; k++) {
if (n1.mod(new BigInteger(String.valueOf(k))).equals(BigInteger.ZERO) &&
n2.mod(new BigInteger(String.valueOf(k))).equals(BigInteger.ZERO))
gcd = k;
}
return gcd;
}
/** Return numerator */
public BigInteger getNumerator() {
return numerator;
}
/** Return denominator */
public BigInteger getDenominator() {
return denominator;
}
/** Add a rational number to this rational */
public Rational add(Rational secondRational) {
BigInteger n =
numerator.multiply(secondRational.getDenominator())
.add(denominator.multiply(sec
ondRational.getNumerator()));
BigInteger d = denominator.multiply(secondRational.getDenominator());
return new Rational(n, d);
}
/** Subtract a rational number from this rational */
public Rational subtract(Rational secondRational) {
BigInteger n =
(numerator.multiply(secondRational.getDenominator()))
.subtract(denominator.multiply(secondRational.getNumerator()));
BigInteger d = denominator.multiply(secondRational.getDenominator());
return new Rational(n, d);
}
/** Multiply a rational number to this rational */
public Rational multiply(Rational secondRational) {
BigInteger n = numerator.multiply(secondRational.getNumerator());
BigInteger d = denominator.multiply(secondRational.getDenominator());
return new Rational(n, d);
}
/** Divide a rational number from this rational */
public Rational divide(Rational secondRational) {
BigInteger n = numerator.multiply(secondRational.getDenominator());
BigInteger d = denominator.multiply(secondRational.numerator);
return new Rational(n, d);
}
/** Compute the square of this rational number*/
public Rational square() {
BigInteger n = numerator.multiply(numerator);
BigInteger d = denominator.multiply(denominator);
return new Rational(n, d);
}
/** toString */
public String toString() {
return numerator + "/" + denominator;
}
}
and this is the testRational class
import java.math.BigInteger;
public class TestRational {
public static void main(String[]args){
int y = 1;
BigInteger i=new BigInteger(String.valueOf(1));
BigInteger a=new BigInteger(String.valueOf(2));
BigInteger b=new BigInteger(String.valueOf(3));
BigInteger c=new BigInteger(String.valueOf(5));
Rational sum = new Rational(BigInteger.ZERO,a);
Rational r0 = new Rational(b,b.add(i));
Rational r2 = new Rational(a,c);
Rational r3 = new Rational(a,c);
Rational s1 = r3.multiply(r2);
Rational s2 = r3.square();
Rational s3 = r2.divide(r3);
Rational r1 = new Rational(i,a);
do{
sum = sum.add(r0);
b = b.add(a);
y++;
}while(y<49);
System.out.println(sum.multiply(sum));
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(r0);
}
}
The purpose of this code is to calculate (1/2+3/4+...+99/100)^2. But my loop can't be executed correctly.
The result of r1 is 3/4 instead of 99/100, what's wrong with my code?
I think my loop can be run because the y I can get it correctly.
So how can i correct my code and make it able to calculate (1/2+3/4+...+99/100)^2 ? Thank you for answering.
The purpose of this code is to calculate (1/2+3/4+...+99/100)^2. But my loop can't be executed correctly.
The result of r1 is 3/4 instead of 99/100, what's wrong with my code?
I think my loop can be run because the y I can get it correctly.
So how can i correct my code and make it able to calculate (1/2+3/4+...+99/100)^2 ? Thank you for answering.
Let's write it less confusingly, without all the unnecessary stuff and confusing loop. The definition of the sum is (1/2 + 3/4 ... 99/100) so let's start by creating all the fractions in the sum:
for (int i = 1; i <= 99; i += 2) {
BigRational t = new BigRational(BigInteger.valueOf(i), BigInteger.valueOf(i + 1));
}
They have to be summed, so there has to be a variable declared outside the loop to sum up all those fractions into:
Rational sum = new Rational();
for (int i = 1; i <= 99; i += 2) {
Rational t = new Rational(BigInteger.valueOf(i), BigInteger.valueOf(i + 1));
sum = sum.add(t);
}
Then square that and you have your answer. I get:
87593039510089573189394173247956745677798336081
-----------------------------------------------
38416307357189261992010230523038591203840000
Which I can't verify but it looks reasonable enough. The expected answer is "a bit less than 502" (because it's the square of 50 terms that are nearly 1, if 0.5 can be called that) and this is close enough.
By the way, stop using String.valueOf everywhere in Rational. Just work with numbers. And BigInteger already implements gcd, you don't have to write your own (less efficient) version. I had to replace this otherwise it took too long.
It's not clear what your sequence of numbers is, but I will go with the following assumption:
If your goal is the simply return the value of (1/2 + 3/4 + 5/6 + ... + 97/98 + 99/100) ^ 2. Then I would suggest the following:
//This method will return the value of (1/2 + 3/4 + 5/6 + ... + 97/98 + 99/100) ^ 2
public int calc(){
double denominator = 2;
double numerator = denominator - 1; //in your sequence, numerator is always 1 less than denominator
double sum = 0;
while(denominator <= 100){
sum = sum + (numerator / denominator); //shorthand sum += (numerator / denominator);
denominator = denominator + 2; //shorthand denominator += 2;
numerator = denominator - 1;
}
return sum * sum; //this is equivalent to sum ^ 2
}
I think my program is skipping my while loop, but I'm honestly not sure exactly what is happening. The function is supposed to reduce fractions by finding the GCD and then dividing numerator and denominator by that number.
class Rational {
private int numerator, denominator;
//Constructor
public Rational (int num, int den) {
numerator = num;
denominator = den;
}
//Method for multiplying fractions
public Rational times (Rational that) {
Rational x = new Rational (this.numerator*that.numerator, this.denominator*that.denominator);
x = x.reduce();
return x;
}
//Method for displaying fractions as strings
public String toString() {
return new String(numerator+"/"+denominator);
}
//Method for adding fractions
public Rational plus(Rational that) {
Rational x = new Rational ((this.numerator*that.denominator)+(that.numerator*this.denominator),
this.denominator*that.denominator);
//x = x.reduce();
return x;
}
//Method for subtracting fractions
public Rational minus(Rational that) {
Rational x = new Rational ((this.numerator*that.denominator)-(that.numerator*this.denominator),
this.denominator*that.denominator);
//x = x.reduce();
return x;
}
//Method for dividing fractions
public Rational divideBy(Rational that) {
Rational x = new Rational (this.numerator*that.denominator, this.denominator*that.numerator);
//x = x.reduce();
return x;
}
public Rational reduce() {
int a = Math.abs(this.numerator);
int b = Math.abs(this.denominator);
int c = Math.min(a, b);
System.out.println(c);
System.out.println(a%c);
System.out.println(b%c);
if (a==0) {
return new Rational (0,1);
}
else {
while (((a%c)!= 0) && ((b%c)!= 0)) {
c = c-1;
System.out.println(c);
}
System.out.println(c);
return new Rational (this.numerator/c,this.denominator/c);
}
}
}
public class RationalTester {
public static void main(String[] args) {
Rational x = new Rational (6,4); //The fraction 6/4
Rational y = new Rational (5,2); //The fraction 5/2
Rational z = x.times(y); //Their product
Rational w = x.plus(y); //Their sum
Rational v = x.minus(y); //Their difference
Rational u = x.divideBy(y); //Their quotient
JOptionPane.showMessageDialog(null, x.toString()+" * "+y.toString()+" = "+z.toString());
JOptionPane.showMessageDialog(null, x.toString()+" + "+y.toString()+" = "+w.toString());
JOptionPane.showMessageDialog(null, x.toString()+" - "+y.toString()+" = "+v.toString());
JOptionPane.showMessageDialog(null, x.toString()+" / "+y.toString()+" = "+u.toString());
}
}
I'm getting the absolute value of the numerator and denominator to ensure that if the fraction is negative I'll be keeping that at the end. If the numerator is 0, I was asked to return (0,1). The question is about the while loop... it seems that it's being skipped completely. Any suggestions?
Because always its condition is false.
In the first lines you set c equal to either a or b. So there are two possibilities:
If c == a, then a%c will be zero. So the while condition is false.
If c == b, then b%c will be zero. So the while condition is false.