473,785 Members | 2,221 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Homework HELP!!! Add/Sub/Mult/Div Fractions

74 New Member
I am having trouble figuring out how to add, subtract, multiply, and divide fractions in my Java program. First off I will tell you what I already did. At first, the assignment was to:

Define a class called Rational. This class is used to represent a ratio of two integers. Include mutator functions that allow the user to set the numerator or denominator as a double. Include additional member function that outputs the value of the fraction reduced to lowest terms. This will require finding the greatest common divisor for the numerator and denominator, then dividing both by that number. Embed your class in a test program.

Okay so I did all of that fine. Everything worked and it was all good, but then, my teacher wanted us to insert another fraction to the mix to do the math operations on it. I am having trouble figuring out how to do that. I keep getting errors upon errors. Also, I am having trouble reducing the fractions now since a new fraction is now in the program.

So, I am asking anyone to help assist me in fixing this problem. Any feedback whatsoever would be greatly appreciated. If you need any more information on the program, please let me know! Thanks!

P.S. Here is my program:



/**
Description: Program to represent a ratio of two integers.
Author:
Email Address:
Last Changed: September 25, 2006
**/

import java.util.Scann er;
import java.text.Decim alFormat;

public class Rational1
{
public static int num1; //num1 = numerator of first fraction
public static int den1; //den1 = denominator of first fraction
public static int num2; //num2 = numerator of second fraction
public static int den2; //den2 = denominator of second fraction

public Rational1()
{
num1 = 0;
num2 = 0;
den1 = 0;
den2 = 0;

}

public Rational1 (int n1, int d1, int n2, int d2)
{
num1 = n1;
den1 = d1;
num2 = n2;
den2 = d2;

if((d1 == 0) || (d2 == 0))
{
System.out.prin tln("Error - denominator cannot be zero!");
}
}

public static void main(String[] args)
{
int lowestNum1 = 0;
int lowestDen1 = 0;
int lowestNum2 = 0;
int lowestDen2 = 0;
int gcd = 0;

System.out.prin tln("Welcome to the world of ratios!");
Rational1 yourRatio = new Rational1();
yourRatio.setRa tio();
System.out.prin tln("Your first fraction: " + num1 + "/" + den1);
System.out.prin tln("Your numerator as a double: ");
yourRatio.toDou ble(num1, num2);
System.out.prin tln("Your denominator as a double: ");
yourRatio.toDou ble(den1, den2);
gcd = yourRatio.gcd(n um1, den1);
System.out.prin tln("Your first fraction's GCD: " + gcd);
lowestNum1 = yourRatio.reduc eNum(num1, gcd);
lowestDen1 = yourRatio.reduc eDen(den1, gcd);
System.out.prin tln("Your reduced fraction:" + lowestNum1 + "/" + lowestDen1);
System.out.prin tln("Your second fraction: " + num2 + "/" + den2);
System.out.prin tln("Your numerator as a double: ");
// yourRatio.toDou ble(num2);
System.out.prin tln("Your denominator as a double: ");
// yourRatio.toDou ble(den2);
gcd = yourRatio.gcd(n um2, den2);
System.out.prin tln("Your second fraction's GCD: " + gcd);
lowestNum2 = yourRatio.reduc eNum(num2, gcd);
lowestDen2 = yourRatio.reduc eDen(den2, gcd);
System.out.prin tln("Your reduced fraction:" + lowestNum2 + "/" + lowestDen2);
System.out.prin tln("Thank you for visiting!");
}

public void setRatio()
{
System.out.prin tln("Enter an integer for the numerator followed by another integer for the denominator to make a ratio.");
System.out.prin tln("(Do not use the / sign to separate the numbers, just insert a space.)");
Scanner ratio = new Scanner(System. in);
num1 = ratio.nextInt() ;
den1 = ratio.nextInt() ;
num2 = ratio.nextInt() ;
den2 = ratio.nextInt() ;
}

public void toDouble(int n1, int n2)
{
double dubN1;
double dubN2;
dubN1 = n1;
dubN2 = n2;

System.out.prin tln(dubN1);
System.out.prin tln(dubN2);
}

/* public static int abs(int n, int d)
{
n = abs(n); //n = numerator
d = abs(d); //d = denominator

while(n !=d)
{
if(n > d)
{
n = n - d;
t = n;
}
else
{
n = d - n;
d = t;
}
g = n;
}
} */

/* public static int abs(int n)
{
return n > 0 ? n : - n;
}*/

public static int gcd(int a, int b)
{
/* int t; //t = temp
n = abs(n);
d = abs(d);

while(n != d)
{
if(n > d)
{
n = n - d;
t = n;
}
else
{
n = n - d;
d = t;
}
return n;
*/
if(b == 0)
{
return a;
}
else
{
return gcd(b, a % b);
}

}

public void reduce()
{
int n1 = num1;
int d1 = den1;
int n2 = num2;
int d2 = den2;
int g = gcd(n, m);

num1 = num1 / g;
den1 = den1 / g;
num2 = num2 / g;
den2 = den2 / g;
}

public int reduceNum(int a, int gcd)
{
int rNum1 = a / gcd;
int rNum2 = a / gcd;

return rNum1;
return rNum2;
}

public int reduceDen(int b, int gcd)
{
int rNum1 = b / gcd;
int rNum2 = b / gcd;

return rNum1;
return rNum2;
}

public Rational1 add(Rational1 Q)
{
Rational1 R;
int den = den1 * den2;
int num = den2 * num1 + den1 * num2;
R = new Rational1(n, d);
R = R.reduce();
return R;
}

public Rational1 multiply(Ration al1 Q)
{
Rational1 R;
int den = den1 * den2;
int num = num1 * num2;
R = new Rational1(n,d);
R = R.reduce();
return R;
}

public Rational1 subtract(Ration al1 Q)
{
Rational1 R;
int den = den1 * den2;
int num = den2 * num1 = den1 * num2;
R = R.reduce();
return R;
}

public Rational1 divide(Rational 1 Q)
{
Rational1 R;
int den = den1 * den2;
int num = num1 / num2;
R = R.reduce();
return R;
}

public static void mathOp(int num1, int den1, int num2, int den2, char op)
{
Rational1 result = new Rational1(); //just in case

f1.write();
prt(op);
f2.write();
prt( " = " );
switch(op)
{
case '+':
result = num1 * den2 + num2 * den1;
break;
case '-':
result = num1 * den2 - num2 * den1;
break;
case '*':
result = num1 * num2;
result = den1 * den2;
break;
case '/':
result = num1 / num2;
result = den1 / den2;
break;
default:
prtln( "Operator!? ..." );
}

result.write( );
DecimalFormat threeDigits = new DecimalFormat(" #0.000");
prtln( " = " + (threeDigits.fo rmat(Result.toD ouble( ))));
}
}
Sep 25 '06 #1
1 8568
r035198x
13,262 MVP
Next time you want to post code, please use code tags.
You could have given your variables names like numerator, denominator, etc.
You do not need to define the other fraction inside your Rational class. It is in fact a Rational itself. Declare it in the main method where you want to test it.
The switch construct should be avoided where possible. In this case, I would suggest you define methods inside your Rational class to perform the arithmetic operations.(If you do not understand this point, have a look at the definition of the java.math.BigDe cimal class.
Sep 25 '06 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

4
2976
by: Allens Mail | last post by:
Help, Due Mon I cant find the error. Keeps saying illegal token } have gone though code and balance all French braces and parenthesis. Please help going crazy. Code below Thanks Allen //************************************************************************** *******
3
3936
by: Amy | last post by:
Hi, I have 6 If Then Else statements I was supposed to write. I did so but I know that they have to be wrong because they all look the same. Could someone take a look at them and point me in the right direction about what I am not doing correctly? 1.. Write an If Then Else statement that displays the string "Pontiac" in the CarMakeLabel control if the CarTextBox control contains the string "Grand Am" (in any case).
7
2059
by: mastern200 | last post by:
For Homework, i have to debug a program (I am a noob!) it is a voting program where you put in the amount of votes a certain candidate gets and evaluates by showing how many votes, what percentage of votes, and total. Problem is that it rounds everything and doesnt show what it is supposed to show. I got this far... Please help! #include <iostream> #include "string.h" using namespace std; int main() {
1
1581
by: mastern200 | last post by:
I need some homework help with an assignment due wed. I need to make a program where in this program calculates the average of a set of test scores. The program will ask the user how many scores there will be. The user will be prompted to enter score 1, score 2, etc. After the scores are entered the computer will print the total number of points, the average score, and the number of scores. The program will ask the user if he/she wants...
2
1652
by: mia23 | last post by:
Hello, I am a java beginner and I need series help in solving this program; my assignment is due after 2 days and I can't understand this program . This is THE PROGRAM:  The ABC medical clinic needs your help in building a Java application that can help in keeping track of patients, appointments, and clinic activities.  Create a class Patient from which we can create objects to handle information about different patients. Each patient is...
5
2998
by: karafire2003 | last post by:
I was wondering if someone can help me with my homework. here's the assignment: a. Write a C program that has a declaration in main() to store the string "What's for lunch?" into an array named message. There should be a function call to restaurant() that accepts the message as an argument named menu and then displays the message using the pointer notation *(menu + i). b. Modify this restaurant() function to alter the address in message....
1
1564
by: itgetsharder | last post by:
Hey, i was wondering if anyone could help me. i have two questions that i cannot complete for a homework assignment: This method should convert its parameter (a string like "3.1415") to the corresponding value of type double. If the string supplied is not a valid number, it should return 0.0 as its result. Note that you can use the method Double.parseDouble() to do the hard work for you. ...
2
1433
by: DonE | last post by:
Help me please. I am having problems with my homework assignment. We are to create a product class that hold the item number, the name of the product, the number of units in stock, and the price of each unit. Here is my problem. I have written the program ( I use netbean) and I have encountered plenty of errors. The error messages that I get are as follows: illegal start type cannot find symbol operator cannot be applied assignment to...
1
2266
by: 1337kamikaze | last post by:
I can't get the common denominator to work. Please help. import java.util.*; import java.lang.*; public class Fraction { /** * @param args
0
9647
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9489
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10162
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10100
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8988
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7509
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6744
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5396
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3665
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.