Interface
package PJ1;
public interface SimpleFractionInterface
{
/** Task: Sets a fraction to a given value.
* @param num is the integer numerator
* @param den is the integer denominator
* @throw ArithmeticException if denominator is 0 */
public void setSimpleFraction(int num, int den);
/** Task: convert a fraction to double value
* @return the double floating point value of a fraction */
public double toDouble();
/** Task: Adds two fractions.
* @param secondFraction is a fraction that is the second operand of the addition
* @return a fraction which is the sum of the invoking fraction and the secondFraction */
public SimpleFractionInterface add(SimpleFractionInterface secondFraction);
/** Task: Subtracts two fractions.
* @param secondFraction a fraction that is the second operand of the subtraction
* @return a fraction which is the difference of the invoking fraction and the second operand */
public SimpleFractionInterface subtract(SimpleFractionInterface secondFraction);
/** Task: Multiplies two fractions.
* @param secondFraction a fraction that is the second operand of the multiplication
* @return a fraction which is the product of the invoking fraction and the secondFraction*/
public SimpleFractionInterface multiply(SimpleFractionInterface secondFraction);
/** Task: Divides two fractions.
* @param secondFraction a fraction that is the second operand of the division
* @return a fraction which the quotient of the invoking fraction and the secondFraction
* @throw FractionException if secondFraction is 0 */
public SimpleFractionInterface divide(SimpleFractionInterface secondFraction);
/** Task: Get\'s the fraction\'s reciprocal
* @return the reciprocal of the invoking fraction
* @throw FractionException if the new number with denominator is 0*/
public SimpleFractionInterface getReciprocal();
}
exception class
package PJ1;
public class SimpleFractionException extends RuntimeException
{
public SimpleFractionException()
{
this(\"\");
}
public SimpleFractionException(String errorMsg)
{
super(errorMsg);
}
}
class with main method
package PJ1;
public class SimpleFraction implements SimpleFractionInterface, Comparable
{
// integer numerator and denominator
private int num;
private int den;
public SimpleFraction()
{
setSimpleFraction(0,1);// default numbers
} // end of the default constructor
public SimpleFraction(int num, int den)
{
setSimpleFraction(num, den);//
} // end constructor
public void setSimpleFraction(int num, int den)
{
if (den == 0)
throw new SimpleFractionException(\"denominator cannot be 0\");
else{
this.num= num;
this.den= den;
}
reduceSimpleFractionToLowestTerms();
} // end setSimpleFraction
public double toDouble()
{
// return double floating point value
return (double) num/den;
} // end toDouble
public SimpleFractionInterface add(SimpleFractionInterface secondFraction)
{
SimpleFraction secondFraction2;
secondFraction2 = (SimpleFraction) secondFraction;
// a/b + c/d is (ad + cb)/(bd)
int newNum = num*secondFraction2.getDen() + sec.
The following is the (incomplete) header file for the class Fracti.pdf4babies2010
The following comparative income statement (in thousands of dollars) for the two recent fiscal
years was adapted from the annual report of Speedway Motorsports, Inc., owner and operator of
several major motor speedways, such as the Atlanta, Texas, and Las Vegas Motor Speedways.
Current Year Previous Year 2 Revenues: 3 Admissions 4Event-related revenue $104,312.00
$116,644.00 131,164.00 170,368.00 65,824.00 $472,000.00 $484,000.00 42,544.00 180,304.00
44,840.00 NASCAR broadcasting revenue Other operating revenue 7 Total revenue 8 Expenses
and other: 9 Direct expense of events 10 NASCAR purse and sanction fees 91,568.00
$101,640.00 117,612.00 20,328.00 220,220.00 424800.00 $459,800.00 $24,200.00 118,000.00
19,352.00 195,880.00 11 Other direct expenses 2 General and administrative 13 Total expenses
and other Income from continuing operations $47,200.00 14 Required A. Prepare a comparative
income statement for these two years in vertical form, stating each item as a percent of revenues.
Enter all amounts as positive numbers. Rounding instructions
Solution
VERTICAL ANALYSIS OF INCOME STATEMENT Particulars Current Year
Amount Current Year Percentage Previous Year Amount Previous Year Percentage
Admissions $ 1,04,312.00 22.10% $ 1,16,644.00 24.10% Event Related revenue $ 1,42,544.00
30.20% $ 1,31,164.00 27.10% NASCAR Broadcasting Revenue $ 1,80,304.00 38.20% $
1,70,368.00 35.20% Other Operating Income $ 44,840.00 9.50% $ 65,824.00 13.60%
Total Revenue $ 4,72,000.00 100.00% $ 4,84,000.00 100.00% Expenses and others
Direct expenses of events $ 91,568.00 19.40% $ 1,01,640.00 21.00% NASCAR purse and
sanction fees $ 1,18,000.00 25.00% $ 1,17,612.00 24.30% Other direct expenses $ 19,352.00
4.10% $ 20,328.00 4.20% General and adminstrative $ 1,95,880.00 41.50% $ 2,20,220.00
45.50% Total Expenses and others $ 4,24,800.00 90.00% $ 4,59,800.00 95.00% Income
from continuing operation $ 47,200.00 10.00% $ 24,200.00 5.00%.
PROGRAM 2 – Fraction Class Problem For this programming as.pdfezonesolutions
PROGRAM 2 – Fraction Class
Problem For this programming assignment, you are to implement the Fraction class design
given below (and discussed in class). You are also to develop an appropriate test driver that
thoroughly tests the class.
Fraction Class Design Implement the following class design. Make sure to use implement the
methods to have the same names as given below, with the same number and types of parameters.
public class Fraction {
private int numer;
private int denom;
// alternate constructor
public Fraction(int numer, int denom)
throws InvalidDenominatorException {
}
// copy constructor
public Fraction(Fraction otherFrac) {
}
// getters
public int getNumer() {
}
public int getDenom() {
}
// standard methods
public String toString() {
}
public boolean equals(Fraction rFrac) {
}
// fraction operators
public Fraction add(Fraction rFrac) {
}
public Fraction sub(Fraction rFrac) {
}
public Fraction mult(Fraction rFrac) {
}
public Fraction div(Fraction rFrac) {
}
public boolean isSimplestForm() {
}
public Fraction reduce() {
}
public boolean properFrac() {
}
public Fraction abs() {
}
public boolean lessThan(Fraction rFrac) {
}
public boolean greaterThan(Fraction rFrac) {
}
public double convertToDecimal() {
}
public Fraction invert() {
}
}
Note that objects of type Fraction are immutable. Also, the alternate constructor throws an
InvalidDenominatorException if passed a denominator value of 0. This exception type is not
predefined in Java, so you must define it as follow as another class in your Java project files:
public class InvalidDenominatorException extends RuntimeException { } // nothing to
implement
This creates an exception of type RuntimeException. RuntimeExceptions do not need to be
caught when thrown. However, your test driver should have the code for catching this exception
where appropriate.
For example, if your test driver excutes the following,
Fraction frac1 = new Fraction(1,2);
then there is no need to catch the possible exception, since it is clear that the denominator is not
0. However, if the value are input by the user, then there is a chance that a denominator vaue of 0
could be entered, and therefore the code for catching the possible exception is needed,
int numer, denom;
Fraction frac1;
Scanner input = new Scanner(System.in);
Boolean valid_input = false;
while (!valid_input) try {
System.out.print(“Enter numerator denominator: “);
numer = input.nextInt();
denom = input.nextInt();
frac1 = new Fraction(numer,denom);
valid_input = true;
}
catch (InvalidDenominatorException e) {
System.out.println(“Denominator of Zero found – Please reenter”);
}
catch (InputMismatchException e) {
System.out.println(“Non-digit character found – Please reenter”);
} etc.
Considerations
Makes sure the equals method returns true for any two fractions that are arithmetically equal.
Make sure that the equals, lessThan and greaterThan methods do not alter the values of the
fractions being compared. You may consider the use of private methods .
Java Programpublic class Fraction { instance variablesin.pdfaroramobiles1
Java Program
public class Fraction {
//instance variables
int num;
int den;
//default construtcor
Fraction()
{
num=0;
den=1;
}
//parametrized constructor
Fraction(int n,int d)
{
num=n;
den=d;
}
//print fraction object
public void print()
{
System.out.println(num+\"/\"+den);
}
//return double value of fraction
public void printAsDouble()
{
try
{
double div=(double)num/(double)den;
System.out.println(div);
}
catch(ArithmeticException e)
{
System.out.println(\"infinity\");
}
catch(Exception e)
{
System.out.println(e);
}
}
//add two fractions
public Fraction add(Fraction param)
{
int tnum=(this.num *param.den)+(this.den*param.num);
int tden=this.den*param.den;
this.num=tnum;
this.den=tden;
return this;
}
//multiply two fractions
public Fraction multiply(Fraction param)
{
int tnum=(this.num *param.num);
int tden=this.den*param.den;
this.num=tnum;
this.den=tden;
return this;
}
}
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
Fraction c, d, x; // Fraction objects
System.out.println(\"Enter numerator; then denominator.\");
c = new Fraction(stdIn.nextInt(), stdIn.nextInt());
c.print();
System.out.println(\"Enter numerator; then denominator.\");
d = new Fraction(stdIn.nextInt(), stdIn.nextInt());
d.print();
x = new Fraction(); // create a fraction for number 0
System.out.println(\"Sum:\");
x.add(c).add(d);
x.print();
x.printAsDouble();
x = new Fraction(1, 1); // create a fraction for number 1
System.out.println(\"Product:\");
x.multiply(c).multiply(d);
x.print();
x.printAsDouble();
System.out.println(\"Enter numerator; then denominator.\");
x = new Fraction(stdIn.nextInt(), stdIn.nextInt());
x.printAsDouble();
} //end main Modify the code so that it can handle negative numerators and negative
denominators, and provide a helping method that performs fraction reduction. Sample session
using negative numbers and reduction Enter numerator, then denominator. -5 -8 5/8 Enter
numerator, then denominator. 4 -10 2/5 Sum: 9/40 0.225 Product: 0.25 Enter numerator, then
denominator. 0 -0 indeterminate
Solution
//Fraction.java
import java.util.Scanner;
public class Fraction {
//instance variables
int num;
int den;
//default construtcor
Fraction()
{
num=0;
den=1;
}
// greatest common divisor to reduce fraction
int gcd(int n1, int n2)
{
if (n2 != 0)
return gcd(n2, n1 % n2);
else
return n1;
}
//parametrized constructor
Fraction(int n,int d)
{
num=n;
den=d;
if(d == 0)
{
System.out.println(\"indeterminate\");
System.exit(1);
}
int hcf = gcd(num,den);
num = num/hcf;
den = den/hcf;
}
//print fraction object
public void print()
{
if( (num < 0 && den > 0))
System.out.println(num+\"/\"+den);
else if((num > 0 && den < 0))
System.out.println(\"-\" + num+\"/\"+ (-1*den));
else if(num < 0 && den < 0)
System.out.println( (-1*num)+\"/\"+ (-1*den));
else
System.out.println(num+\"/\"+den);
}
//return double value of fraction
public void printAsDouble()
{
try
{
double div=(double)num/(double)den;
System.out.println(div);
}
catch(ArithmeticException e.
AnswerNote Provided code shows several bugs, hence I implemented.pdfanurag1231
Answer:
Note: Provided code shows several bugs, hence I implemented a separate code as per the given
program specifications
Program code:
import java.util.Scanner;
//declares fraction class
class Fraction
{
//private data members for the class
private int numerators,denominators;
//default constructor
public Fraction()
{
}
//parameterised constructor for the class
public Fraction(int numerators, int denominators)
{
//assigns numerator
this.numerators = numerators;
//checks the denominator
if(denominators == 0)
{
System.out.println(\"denominator Shouldn\'t be ZERO \");
System.out.println(\"Program Exiting.....\");
System.exit(0);
}
this.denominators = denominators;
}
//parameterised constructor
public Fraction(int numerators)
{
this.numerators = numerators;
}
//method TO string
public String toString()
{
return \"\"+numerators+\" / \"+denominators;
}
//methods Equals()
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Fraction other = (Fraction) obj;
if (this.numerators != other.numerators) {
return false;
}
if (this.denominators != other.denominators) {
return false;
}
return true;
}
//method GCD declaration
public int GCD(int a, int b)
{
//declares local variables
int x = 0, GCD = 0;
int max = a > b ? a : b;
int min = a < b ? a : b;
for(int i = 1; i <= min; i++)
{
x = max * i;
if(x % min == 0)
{
GCD = x;
break;
}
}
//returns GCD
return GCD;
}
//Method to read
public static Fraction read()
{
Scanner sc1 = new Scanner(System.in);
System.out.print(\"Enter Fraction numerators : \");
int num1 = sc1.nextInt();
System.out.print(\"Enter Fraction denominators : \");
int den1 = sc1.nextInt();
System.out.println();
Fraction f1 = new Fraction(num1,den1);
return f1;
}
//Method definition to add()
public Fraction add(Fraction other1)
{
int GCD = GCD(this.denominators,other.denominators);
int numb1 = this.numerators * (GCD/this.denominators);
int numb2 = other1.numerators *(GCD/other.denominators);
int num1 = 0, den1 = 0;
num1 = numb1 + numb2;
den1 = GCD;
return new Fraction(num1,den1);
}
//method definition to add()
public Fraction add(int temp1)
{
//defines the number variable
int num1 = this.denominators * temp1 + this.numerators;
return new Fraction(num1,this.denominators);
}
//method definition to subract
public Fraction subtract(Fraction other1)
{
int GCD = GCD(this.denominators,other.denominators);
int numb1 = this.numerators *(GCD/this.denominators);
int numb2 = other1.numerators *(GCD/other1.denominators);
int num1 = 0, den1 = 0;
num1 = numb1 - numb2;
den1 = GCD;
return new Fraction(num1,den1);
}
//Method definition to multiply
public Fraction multiply(Fraction other1)
{
int num1 = 0, den1 = 0;
num1 = this.numerators * other1.numerators;
den1 = this.denominators * other1.denominators;
return new Fraction(num1,den1);
}
//method definition to Multiply
public Fraction multiply(int temp1)
{
int num 1= this.numerators * temp1;
return new Fraction(num1,this.denomina.
operating system ubuntu,linux,MacProgram will work only if you g.pdfaptcomputerzone
//operating system ubuntu,linux,Mac
Program will work only if you give command like
sum 2 3 or
sum 4 (sub 4 3)
#include
#include
#include
#include
/*Sum function implementation*/
int sum(int number1,int number2){
return number1+number2;
}
/*sub function implementation*/
int sub(int number1,int number2){
return number1-number2;
}
/*mul function implementation*/
int mul(int number1,int number2){
return number1*number2;
}
/*divide function implementation*/
float divide(int number1,int number2){
if(number2==0){
printf(\"We can not divide by 0 \ \");
return 0.0f;
}
return (float)(number1/number2);
}
char *substring(char *string, int position, int length)
{
char *pointer;
int c;
pointer = malloc(length+1);
if (pointer == NULL)
{
printf(\"Unable to allocate memory.\ \");
exit(1);
}
for (c = 0 ; c < length ; c++)
{
*(pointer+c) = *(string+position-1);
string++;
}
*(pointer+c) = \'\\0\';
return pointer;
}
/*Main Function start*/
int main(int argc, char *argv[]){
/*Variable declarations*/
int number1,number2;
char *operator,*str1,*str2;
char line[50];
char s[2] = \" \";
int errorFlag=0;// checking if user entered more then one operands
while(1){
/*User input*/
printf(\"Please Enter the command \");
gets(line);
int len=0;
for(int i=0; line[i]!=\'\\0\'; ++i){len++;}
if(len==0){
return 1;
}
/*Spliting into Tokens*/
operator = strtok(line, \" \");
if(strcmp(operator,\"bye\")==0){
break;
}
/*String to integer --- token1*/
number1=atoi(strtok(NULL, s));
/*Removing ( and ) from String*/
str2=strtok(NULL, s);
char *content;int length=0;
for(int i=0; str2[i]!=\'\\0\'; ++i){length++;}
if(str2[0]==\'(\'){
content=substring(str2,2,length-1);
char *opr=content;
int n1=atoi(strtok(NULL, s));
int n2=atoi(strtok(NULL, s));
/*If user entered more then two operands then it will return some token otherwise it will
return NULL pointer*/
if(strtok(NULL, s)!=NULL){
printf(\"You need to enter operator operand1 operand2 \ \");
errorFlag=1;
}else{
if(strcmp(opr,\"sum\")==0){
number2=sum(n1,n2);
}else if(strcmp(opr,\"sub\")==0){
number2=sub(n1,n2);
}else if(strcmp(opr,\"mul\")==0){
number2=mul(n1,n2);
} else if(strcmp(opr,\"div\")==0){
number2=divide(n1,n2);
}
}
}else{
number2=atoi(str2);
/*If user entered more then two operands then it will return some token otherwise it will return
NULL pointer*/
if(strtok(NULL, s)!=NULL){
printf(\"You need to enter operator operand1 operand2 \ \");
errorFlag=1;
}
}
if(errorFlag!=1){
/*Checking operator by strcmp function*/
if(strcmp(operator,\"sum\")==0){
printf(\"Result %d \ \",sum(number1,number2));
}else if(strcmp(operator,\"sub\")==0){
printf(\"Result %d \ \",sub(number1,number2));
}else if(strcmp(operator,\"mul\")==0){
printf(\"Result %d \ \",mul(number1,number2));
} else if(strcmp(operator,\"div\")==0){
printf(\"Result %.2f \ \",divide(number1,number2));
}
}
}
return 0;
}
/*******************Output***********************/
gopal@gopal:~/Desktop/chegg$ gcc Calculator.c
Calculator.c: In function ‘main’:
Calculator.c:67:3: warning: implici.
Write a program that works with fractions. You are first to implemen.pdfleventhalbrad49439
Write a program that works with fractions. You are first to implement three methods, each to
perform a different calculation on a pair of fractions: subtract, multiply, and divide. For each of
these methods, you are supplied two fractions as arguments, each a two-element array (the
numerator is at index 0, the denominator is at index 1), and you are to return a resulting,
simplified fraction as a new two-element array (again, with the numerator at index 0, and
denominator at index 1). You have been provide an add method as an example. You must
compute the resulting fraction using fraction-based math (working with numerators and
denominators) – do not convert the fractions to double values (like 1.5), do the math, and convert
back to a fraction. You have been provided a method to simplify a fraction using the gcd method
from the previous lab.
Once the operation methods are complete and pass the JUnit tests, now focus your attention on
the main method. You first need to input the two fractions from the keyboard (numerator then
denominator for each; you can assume integers) as well as one of the four valid operations (+, -,
*, /). Then validate the inputs: make sure a valid operation was input, make sure neither of the
denominators are zero, and make sure that the numerator of the second fraction isn’t zero if the
operation is division (error messages have been provided for each of these situations). Finally,
compute the result of the operation and output the answer. Note that if the denominator of the
answer is 1, you should just output the numerator (this includes if the answer is 0).
Here is the outline code given:
public class LA5a {
/**
* Error to output if either denominator is zero
*/
static final String E_DEN_ZERO = \"Denominator cannot be zero.\";
/**
* Error to output if dividing by zero
*/
static final String E_DIV_ZERO = \"Cannot divide by zero.\";
/**
* Error to output if the operation is invalid
*/
static final String E_OP_INVALID = \"Invalid operation.\";
/**
* Returns the greatest common divisor (gcd) of two integers
*
* @param num1 integer 1
* @param num2 integer 2
* @return gcd of integers 1 and 2
*/
public static int gcd(int num1, int num2) {
int t;
while (num2 != 0) {
t = num2;
num2 = num1 % num2;
num1 = t;
}
return num1;
}
/**
* Returns the simplified form of a fraction
*
* @param f fraction (numerator=[0], denominator=[1])
* @return simplified fraction (numerator=[0], denominator=[1])
*/
public static int[] simplifyFraction(int[] f) {
final int gcd = gcd(f[0], f[1]);
int[] result = {f[0]/gcd, f[1]/gcd};
if ((result[0]<0 && result[1]<0) || (result[1]<0)) {
result[0] = -result[0];
result[1] = -result[1];
}
return result;
}
/**
* Adds two fractions
*
* @param f1 first fraction (numerator=[0], denominator=[1])
* @param f2 second fraction (numerator=[0], denominator=[1])
* @return result of adding parameters (numerator=[0], denominator=[1])
*/
public static int[] addFractions(int[] f1, int[] f2) {
int[] result = new int[2];
resu.
When we test your Fraction.java we will use the given FractionTester.pdfarihantkitchenmart
When we test your Fraction.java we will use the given FractionTester.java file.
Add the following methods to the given Fraction.java file
-public Fraction add( Fraction other) returns a Fraction that is the sum of the two Fractions.
-public Fraction subtract( Fraction other) returns a Fraction that is the difference between this
Fraction minus the other Fraction.
-public Fraction multiply( Fraction other) returns a Fraction that is the product of the two
Fractions.
-public Fraction divide( Fraction other) returns a Fraction that is the quotient of the two
Fractions.
-public Fraction reciprocal() returns a Fraction that is the reciprocal of this Fractions.
-private void reduce() Does not return a Fraction. It just modifies this Fraction by reducing it to
its lowest form.
Every Fraction must reduce at all times. Every new fraction constructed it must be reduced
before the constructor exits. No Fraction at any time may be stored in a form other than its
reduced form.
/* Fraction.java A class (data type) definition file
This file just defines what a Fraction is
This file is NOT a program
** data members are PRIVATE
** method members are PUBLIC
*/
public class Fraction
{
private int numer;
private int denom;
// ACCESSORS
public int getNumer()
{
return numer;
}
public int getDenom()
{
return denom;
}
public String toString()
{
return numer + \"/\" + denom;
}
// MUTATORS
public void setNumer( int n )
{
numer = n;
}
public void setDenom( int d )
{
if (d!=0)
denom=d;
else
{
// error msg OR exception OR exit etc.
}
}
// DEFAULT CONSTRUCTOR - no args passed in
public Fraction( )
{
this( 0, 1 ); // \"this\" means call a fellow constructor
}
// 1 arg CONSTRUCTOR - 1 arg passed in
// assume user wants whole number
public Fraction( int n )
{
this( n, 1 ); // \"this\" means call a fellow constructor
}
// FULL CONSTRUCTOR - an arg for each class data member
public Fraction( int n, int d )
{
setNumer(n);
setDenom(d);
// call your reduce here
}
// COPY CONSTRUCTOR - takes ref to some already initialized Fraction object
public Fraction( Fraction other )
{
this( other.numer, other.denom ); // call my full C\'Tor with other Fraction\'s data
}
private void reduce()
{
// reduces this fraction to lowest form
}
}// EOF
JavaTester file
Solution
/* Fraction.java A class (data type) definition file
This file just defines what a Fraction is
This file is NOT a program
** data members are PRIVATE
** method members are PUBLIC
*/
public class Fraction {
private int numer;
private int denom;
// ACCESSORS
public int getNumer() {
return numer;
}
public int getDenom() {
return denom;
}
public String toString() {
return numer + \"/\" + denom;
}
// MUTATORS
public void setNumer(int n) {
numer = n;
}
public void setDenom(int d) {
if (d != 0)
denom = d;
else {
// error msg OR exception OR exit etc.
}
}
// DEFAULT CONSTRUCTOR - no args passed in
public Fraction() {
this(0, 1); // \"this\" means call a fellow constructor
}
// 1 arg CONSTRUCTOR - 1 arg passed in
// assume user wants who.
The following is the (incomplete) header file for the class Fracti.pdf4babies2010
The following comparative income statement (in thousands of dollars) for the two recent fiscal
years was adapted from the annual report of Speedway Motorsports, Inc., owner and operator of
several major motor speedways, such as the Atlanta, Texas, and Las Vegas Motor Speedways.
Current Year Previous Year 2 Revenues: 3 Admissions 4Event-related revenue $104,312.00
$116,644.00 131,164.00 170,368.00 65,824.00 $472,000.00 $484,000.00 42,544.00 180,304.00
44,840.00 NASCAR broadcasting revenue Other operating revenue 7 Total revenue 8 Expenses
and other: 9 Direct expense of events 10 NASCAR purse and sanction fees 91,568.00
$101,640.00 117,612.00 20,328.00 220,220.00 424800.00 $459,800.00 $24,200.00 118,000.00
19,352.00 195,880.00 11 Other direct expenses 2 General and administrative 13 Total expenses
and other Income from continuing operations $47,200.00 14 Required A. Prepare a comparative
income statement for these two years in vertical form, stating each item as a percent of revenues.
Enter all amounts as positive numbers. Rounding instructions
Solution
VERTICAL ANALYSIS OF INCOME STATEMENT Particulars Current Year
Amount Current Year Percentage Previous Year Amount Previous Year Percentage
Admissions $ 1,04,312.00 22.10% $ 1,16,644.00 24.10% Event Related revenue $ 1,42,544.00
30.20% $ 1,31,164.00 27.10% NASCAR Broadcasting Revenue $ 1,80,304.00 38.20% $
1,70,368.00 35.20% Other Operating Income $ 44,840.00 9.50% $ 65,824.00 13.60%
Total Revenue $ 4,72,000.00 100.00% $ 4,84,000.00 100.00% Expenses and others
Direct expenses of events $ 91,568.00 19.40% $ 1,01,640.00 21.00% NASCAR purse and
sanction fees $ 1,18,000.00 25.00% $ 1,17,612.00 24.30% Other direct expenses $ 19,352.00
4.10% $ 20,328.00 4.20% General and adminstrative $ 1,95,880.00 41.50% $ 2,20,220.00
45.50% Total Expenses and others $ 4,24,800.00 90.00% $ 4,59,800.00 95.00% Income
from continuing operation $ 47,200.00 10.00% $ 24,200.00 5.00%.
PROGRAM 2 – Fraction Class Problem For this programming as.pdfezonesolutions
PROGRAM 2 – Fraction Class
Problem For this programming assignment, you are to implement the Fraction class design
given below (and discussed in class). You are also to develop an appropriate test driver that
thoroughly tests the class.
Fraction Class Design Implement the following class design. Make sure to use implement the
methods to have the same names as given below, with the same number and types of parameters.
public class Fraction {
private int numer;
private int denom;
// alternate constructor
public Fraction(int numer, int denom)
throws InvalidDenominatorException {
}
// copy constructor
public Fraction(Fraction otherFrac) {
}
// getters
public int getNumer() {
}
public int getDenom() {
}
// standard methods
public String toString() {
}
public boolean equals(Fraction rFrac) {
}
// fraction operators
public Fraction add(Fraction rFrac) {
}
public Fraction sub(Fraction rFrac) {
}
public Fraction mult(Fraction rFrac) {
}
public Fraction div(Fraction rFrac) {
}
public boolean isSimplestForm() {
}
public Fraction reduce() {
}
public boolean properFrac() {
}
public Fraction abs() {
}
public boolean lessThan(Fraction rFrac) {
}
public boolean greaterThan(Fraction rFrac) {
}
public double convertToDecimal() {
}
public Fraction invert() {
}
}
Note that objects of type Fraction are immutable. Also, the alternate constructor throws an
InvalidDenominatorException if passed a denominator value of 0. This exception type is not
predefined in Java, so you must define it as follow as another class in your Java project files:
public class InvalidDenominatorException extends RuntimeException { } // nothing to
implement
This creates an exception of type RuntimeException. RuntimeExceptions do not need to be
caught when thrown. However, your test driver should have the code for catching this exception
where appropriate.
For example, if your test driver excutes the following,
Fraction frac1 = new Fraction(1,2);
then there is no need to catch the possible exception, since it is clear that the denominator is not
0. However, if the value are input by the user, then there is a chance that a denominator vaue of 0
could be entered, and therefore the code for catching the possible exception is needed,
int numer, denom;
Fraction frac1;
Scanner input = new Scanner(System.in);
Boolean valid_input = false;
while (!valid_input) try {
System.out.print(“Enter numerator denominator: “);
numer = input.nextInt();
denom = input.nextInt();
frac1 = new Fraction(numer,denom);
valid_input = true;
}
catch (InvalidDenominatorException e) {
System.out.println(“Denominator of Zero found – Please reenter”);
}
catch (InputMismatchException e) {
System.out.println(“Non-digit character found – Please reenter”);
} etc.
Considerations
Makes sure the equals method returns true for any two fractions that are arithmetically equal.
Make sure that the equals, lessThan and greaterThan methods do not alter the values of the
fractions being compared. You may consider the use of private methods .
Java Programpublic class Fraction { instance variablesin.pdfaroramobiles1
Java Program
public class Fraction {
//instance variables
int num;
int den;
//default construtcor
Fraction()
{
num=0;
den=1;
}
//parametrized constructor
Fraction(int n,int d)
{
num=n;
den=d;
}
//print fraction object
public void print()
{
System.out.println(num+\"/\"+den);
}
//return double value of fraction
public void printAsDouble()
{
try
{
double div=(double)num/(double)den;
System.out.println(div);
}
catch(ArithmeticException e)
{
System.out.println(\"infinity\");
}
catch(Exception e)
{
System.out.println(e);
}
}
//add two fractions
public Fraction add(Fraction param)
{
int tnum=(this.num *param.den)+(this.den*param.num);
int tden=this.den*param.den;
this.num=tnum;
this.den=tden;
return this;
}
//multiply two fractions
public Fraction multiply(Fraction param)
{
int tnum=(this.num *param.num);
int tden=this.den*param.den;
this.num=tnum;
this.den=tden;
return this;
}
}
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
Fraction c, d, x; // Fraction objects
System.out.println(\"Enter numerator; then denominator.\");
c = new Fraction(stdIn.nextInt(), stdIn.nextInt());
c.print();
System.out.println(\"Enter numerator; then denominator.\");
d = new Fraction(stdIn.nextInt(), stdIn.nextInt());
d.print();
x = new Fraction(); // create a fraction for number 0
System.out.println(\"Sum:\");
x.add(c).add(d);
x.print();
x.printAsDouble();
x = new Fraction(1, 1); // create a fraction for number 1
System.out.println(\"Product:\");
x.multiply(c).multiply(d);
x.print();
x.printAsDouble();
System.out.println(\"Enter numerator; then denominator.\");
x = new Fraction(stdIn.nextInt(), stdIn.nextInt());
x.printAsDouble();
} //end main Modify the code so that it can handle negative numerators and negative
denominators, and provide a helping method that performs fraction reduction. Sample session
using negative numbers and reduction Enter numerator, then denominator. -5 -8 5/8 Enter
numerator, then denominator. 4 -10 2/5 Sum: 9/40 0.225 Product: 0.25 Enter numerator, then
denominator. 0 -0 indeterminate
Solution
//Fraction.java
import java.util.Scanner;
public class Fraction {
//instance variables
int num;
int den;
//default construtcor
Fraction()
{
num=0;
den=1;
}
// greatest common divisor to reduce fraction
int gcd(int n1, int n2)
{
if (n2 != 0)
return gcd(n2, n1 % n2);
else
return n1;
}
//parametrized constructor
Fraction(int n,int d)
{
num=n;
den=d;
if(d == 0)
{
System.out.println(\"indeterminate\");
System.exit(1);
}
int hcf = gcd(num,den);
num = num/hcf;
den = den/hcf;
}
//print fraction object
public void print()
{
if( (num < 0 && den > 0))
System.out.println(num+\"/\"+den);
else if((num > 0 && den < 0))
System.out.println(\"-\" + num+\"/\"+ (-1*den));
else if(num < 0 && den < 0)
System.out.println( (-1*num)+\"/\"+ (-1*den));
else
System.out.println(num+\"/\"+den);
}
//return double value of fraction
public void printAsDouble()
{
try
{
double div=(double)num/(double)den;
System.out.println(div);
}
catch(ArithmeticException e.
AnswerNote Provided code shows several bugs, hence I implemented.pdfanurag1231
Answer:
Note: Provided code shows several bugs, hence I implemented a separate code as per the given
program specifications
Program code:
import java.util.Scanner;
//declares fraction class
class Fraction
{
//private data members for the class
private int numerators,denominators;
//default constructor
public Fraction()
{
}
//parameterised constructor for the class
public Fraction(int numerators, int denominators)
{
//assigns numerator
this.numerators = numerators;
//checks the denominator
if(denominators == 0)
{
System.out.println(\"denominator Shouldn\'t be ZERO \");
System.out.println(\"Program Exiting.....\");
System.exit(0);
}
this.denominators = denominators;
}
//parameterised constructor
public Fraction(int numerators)
{
this.numerators = numerators;
}
//method TO string
public String toString()
{
return \"\"+numerators+\" / \"+denominators;
}
//methods Equals()
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Fraction other = (Fraction) obj;
if (this.numerators != other.numerators) {
return false;
}
if (this.denominators != other.denominators) {
return false;
}
return true;
}
//method GCD declaration
public int GCD(int a, int b)
{
//declares local variables
int x = 0, GCD = 0;
int max = a > b ? a : b;
int min = a < b ? a : b;
for(int i = 1; i <= min; i++)
{
x = max * i;
if(x % min == 0)
{
GCD = x;
break;
}
}
//returns GCD
return GCD;
}
//Method to read
public static Fraction read()
{
Scanner sc1 = new Scanner(System.in);
System.out.print(\"Enter Fraction numerators : \");
int num1 = sc1.nextInt();
System.out.print(\"Enter Fraction denominators : \");
int den1 = sc1.nextInt();
System.out.println();
Fraction f1 = new Fraction(num1,den1);
return f1;
}
//Method definition to add()
public Fraction add(Fraction other1)
{
int GCD = GCD(this.denominators,other.denominators);
int numb1 = this.numerators * (GCD/this.denominators);
int numb2 = other1.numerators *(GCD/other.denominators);
int num1 = 0, den1 = 0;
num1 = numb1 + numb2;
den1 = GCD;
return new Fraction(num1,den1);
}
//method definition to add()
public Fraction add(int temp1)
{
//defines the number variable
int num1 = this.denominators * temp1 + this.numerators;
return new Fraction(num1,this.denominators);
}
//method definition to subract
public Fraction subtract(Fraction other1)
{
int GCD = GCD(this.denominators,other.denominators);
int numb1 = this.numerators *(GCD/this.denominators);
int numb2 = other1.numerators *(GCD/other1.denominators);
int num1 = 0, den1 = 0;
num1 = numb1 - numb2;
den1 = GCD;
return new Fraction(num1,den1);
}
//Method definition to multiply
public Fraction multiply(Fraction other1)
{
int num1 = 0, den1 = 0;
num1 = this.numerators * other1.numerators;
den1 = this.denominators * other1.denominators;
return new Fraction(num1,den1);
}
//method definition to Multiply
public Fraction multiply(int temp1)
{
int num 1= this.numerators * temp1;
return new Fraction(num1,this.denomina.
operating system ubuntu,linux,MacProgram will work only if you g.pdfaptcomputerzone
//operating system ubuntu,linux,Mac
Program will work only if you give command like
sum 2 3 or
sum 4 (sub 4 3)
#include
#include
#include
#include
/*Sum function implementation*/
int sum(int number1,int number2){
return number1+number2;
}
/*sub function implementation*/
int sub(int number1,int number2){
return number1-number2;
}
/*mul function implementation*/
int mul(int number1,int number2){
return number1*number2;
}
/*divide function implementation*/
float divide(int number1,int number2){
if(number2==0){
printf(\"We can not divide by 0 \ \");
return 0.0f;
}
return (float)(number1/number2);
}
char *substring(char *string, int position, int length)
{
char *pointer;
int c;
pointer = malloc(length+1);
if (pointer == NULL)
{
printf(\"Unable to allocate memory.\ \");
exit(1);
}
for (c = 0 ; c < length ; c++)
{
*(pointer+c) = *(string+position-1);
string++;
}
*(pointer+c) = \'\\0\';
return pointer;
}
/*Main Function start*/
int main(int argc, char *argv[]){
/*Variable declarations*/
int number1,number2;
char *operator,*str1,*str2;
char line[50];
char s[2] = \" \";
int errorFlag=0;// checking if user entered more then one operands
while(1){
/*User input*/
printf(\"Please Enter the command \");
gets(line);
int len=0;
for(int i=0; line[i]!=\'\\0\'; ++i){len++;}
if(len==0){
return 1;
}
/*Spliting into Tokens*/
operator = strtok(line, \" \");
if(strcmp(operator,\"bye\")==0){
break;
}
/*String to integer --- token1*/
number1=atoi(strtok(NULL, s));
/*Removing ( and ) from String*/
str2=strtok(NULL, s);
char *content;int length=0;
for(int i=0; str2[i]!=\'\\0\'; ++i){length++;}
if(str2[0]==\'(\'){
content=substring(str2,2,length-1);
char *opr=content;
int n1=atoi(strtok(NULL, s));
int n2=atoi(strtok(NULL, s));
/*If user entered more then two operands then it will return some token otherwise it will
return NULL pointer*/
if(strtok(NULL, s)!=NULL){
printf(\"You need to enter operator operand1 operand2 \ \");
errorFlag=1;
}else{
if(strcmp(opr,\"sum\")==0){
number2=sum(n1,n2);
}else if(strcmp(opr,\"sub\")==0){
number2=sub(n1,n2);
}else if(strcmp(opr,\"mul\")==0){
number2=mul(n1,n2);
} else if(strcmp(opr,\"div\")==0){
number2=divide(n1,n2);
}
}
}else{
number2=atoi(str2);
/*If user entered more then two operands then it will return some token otherwise it will return
NULL pointer*/
if(strtok(NULL, s)!=NULL){
printf(\"You need to enter operator operand1 operand2 \ \");
errorFlag=1;
}
}
if(errorFlag!=1){
/*Checking operator by strcmp function*/
if(strcmp(operator,\"sum\")==0){
printf(\"Result %d \ \",sum(number1,number2));
}else if(strcmp(operator,\"sub\")==0){
printf(\"Result %d \ \",sub(number1,number2));
}else if(strcmp(operator,\"mul\")==0){
printf(\"Result %d \ \",mul(number1,number2));
} else if(strcmp(operator,\"div\")==0){
printf(\"Result %.2f \ \",divide(number1,number2));
}
}
}
return 0;
}
/*******************Output***********************/
gopal@gopal:~/Desktop/chegg$ gcc Calculator.c
Calculator.c: In function ‘main’:
Calculator.c:67:3: warning: implici.
Write a program that works with fractions. You are first to implemen.pdfleventhalbrad49439
Write a program that works with fractions. You are first to implement three methods, each to
perform a different calculation on a pair of fractions: subtract, multiply, and divide. For each of
these methods, you are supplied two fractions as arguments, each a two-element array (the
numerator is at index 0, the denominator is at index 1), and you are to return a resulting,
simplified fraction as a new two-element array (again, with the numerator at index 0, and
denominator at index 1). You have been provide an add method as an example. You must
compute the resulting fraction using fraction-based math (working with numerators and
denominators) – do not convert the fractions to double values (like 1.5), do the math, and convert
back to a fraction. You have been provided a method to simplify a fraction using the gcd method
from the previous lab.
Once the operation methods are complete and pass the JUnit tests, now focus your attention on
the main method. You first need to input the two fractions from the keyboard (numerator then
denominator for each; you can assume integers) as well as one of the four valid operations (+, -,
*, /). Then validate the inputs: make sure a valid operation was input, make sure neither of the
denominators are zero, and make sure that the numerator of the second fraction isn’t zero if the
operation is division (error messages have been provided for each of these situations). Finally,
compute the result of the operation and output the answer. Note that if the denominator of the
answer is 1, you should just output the numerator (this includes if the answer is 0).
Here is the outline code given:
public class LA5a {
/**
* Error to output if either denominator is zero
*/
static final String E_DEN_ZERO = \"Denominator cannot be zero.\";
/**
* Error to output if dividing by zero
*/
static final String E_DIV_ZERO = \"Cannot divide by zero.\";
/**
* Error to output if the operation is invalid
*/
static final String E_OP_INVALID = \"Invalid operation.\";
/**
* Returns the greatest common divisor (gcd) of two integers
*
* @param num1 integer 1
* @param num2 integer 2
* @return gcd of integers 1 and 2
*/
public static int gcd(int num1, int num2) {
int t;
while (num2 != 0) {
t = num2;
num2 = num1 % num2;
num1 = t;
}
return num1;
}
/**
* Returns the simplified form of a fraction
*
* @param f fraction (numerator=[0], denominator=[1])
* @return simplified fraction (numerator=[0], denominator=[1])
*/
public static int[] simplifyFraction(int[] f) {
final int gcd = gcd(f[0], f[1]);
int[] result = {f[0]/gcd, f[1]/gcd};
if ((result[0]<0 && result[1]<0) || (result[1]<0)) {
result[0] = -result[0];
result[1] = -result[1];
}
return result;
}
/**
* Adds two fractions
*
* @param f1 first fraction (numerator=[0], denominator=[1])
* @param f2 second fraction (numerator=[0], denominator=[1])
* @return result of adding parameters (numerator=[0], denominator=[1])
*/
public static int[] addFractions(int[] f1, int[] f2) {
int[] result = new int[2];
resu.
When we test your Fraction.java we will use the given FractionTester.pdfarihantkitchenmart
When we test your Fraction.java we will use the given FractionTester.java file.
Add the following methods to the given Fraction.java file
-public Fraction add( Fraction other) returns a Fraction that is the sum of the two Fractions.
-public Fraction subtract( Fraction other) returns a Fraction that is the difference between this
Fraction minus the other Fraction.
-public Fraction multiply( Fraction other) returns a Fraction that is the product of the two
Fractions.
-public Fraction divide( Fraction other) returns a Fraction that is the quotient of the two
Fractions.
-public Fraction reciprocal() returns a Fraction that is the reciprocal of this Fractions.
-private void reduce() Does not return a Fraction. It just modifies this Fraction by reducing it to
its lowest form.
Every Fraction must reduce at all times. Every new fraction constructed it must be reduced
before the constructor exits. No Fraction at any time may be stored in a form other than its
reduced form.
/* Fraction.java A class (data type) definition file
This file just defines what a Fraction is
This file is NOT a program
** data members are PRIVATE
** method members are PUBLIC
*/
public class Fraction
{
private int numer;
private int denom;
// ACCESSORS
public int getNumer()
{
return numer;
}
public int getDenom()
{
return denom;
}
public String toString()
{
return numer + \"/\" + denom;
}
// MUTATORS
public void setNumer( int n )
{
numer = n;
}
public void setDenom( int d )
{
if (d!=0)
denom=d;
else
{
// error msg OR exception OR exit etc.
}
}
// DEFAULT CONSTRUCTOR - no args passed in
public Fraction( )
{
this( 0, 1 ); // \"this\" means call a fellow constructor
}
// 1 arg CONSTRUCTOR - 1 arg passed in
// assume user wants whole number
public Fraction( int n )
{
this( n, 1 ); // \"this\" means call a fellow constructor
}
// FULL CONSTRUCTOR - an arg for each class data member
public Fraction( int n, int d )
{
setNumer(n);
setDenom(d);
// call your reduce here
}
// COPY CONSTRUCTOR - takes ref to some already initialized Fraction object
public Fraction( Fraction other )
{
this( other.numer, other.denom ); // call my full C\'Tor with other Fraction\'s data
}
private void reduce()
{
// reduces this fraction to lowest form
}
}// EOF
JavaTester file
Solution
/* Fraction.java A class (data type) definition file
This file just defines what a Fraction is
This file is NOT a program
** data members are PRIVATE
** method members are PUBLIC
*/
public class Fraction {
private int numer;
private int denom;
// ACCESSORS
public int getNumer() {
return numer;
}
public int getDenom() {
return denom;
}
public String toString() {
return numer + \"/\" + denom;
}
// MUTATORS
public void setNumer(int n) {
numer = n;
}
public void setDenom(int d) {
if (d != 0)
denom = d;
else {
// error msg OR exception OR exit etc.
}
}
// DEFAULT CONSTRUCTOR - no args passed in
public Fraction() {
this(0, 1); // \"this\" means call a fellow constructor
}
// 1 arg CONSTRUCTOR - 1 arg passed in
// assume user wants who.
public class Point { Insert your name here private dou.pdfanandshingavi23
public class Point {
/* Insert your name here */
private double x;
private double y;
public static final double EPSILON = 1e-5;
public static boolean debug = false;
// TODO Implement Point.Point(double x, double y)
/**
* instantiate a point \"this.x\" refers to the instance variable of the
* object x refers to the parameter same for this.y and y
*/
public Point(double x, double y) {
// System.out.println(\"Point(x,y) not implemented yet\");
this.x = x;
this.y = y;
}
// TODO Implement Point.Point()
/**
* Point() creates the origin by appropriately calling the general Point
* constructor
*/
public Point() {
// System.out.println(\"Point() not implemented yet\");
this.x = 0;
this.y = 0;
}
// TODO Implement Point.getX
/**
* return x
*/
public double getX() {
// System.out.println(\"getX not implemented yet\");
return this.x;
}
// TODO Implement Point.getY
/**
* return y
*/
public double getY() {
// System.out.println(\"getY not implemented yet\");
return this.y;
}
// Given Point.toString
/**
* convert to String
*/
public String toString() {
return \"(\" + x + \",\" + y + \")\";
}
// TODO Implement Point.equals
/**
*
* param p other point return test for equality using epsilon, because we
* are dealing with doubles,so roundoff can occur
*/
public boolean equals(Point p) {
// System.out.println(\"equals not implemented yet\");
if (p.getX() == this.getX() && p.getY() == this.getY())
return true;
else
return false;
}
// Given equals(Object o)
/**
* We need this equals method for ArrayList, because the generic
* ArrayList is really an ArrayList of Object. In the case of equals, the
* signature is public boolean equals(Object o) and the method below
* overrides the Object equals method and the calls the class\'s
* equals(Point) method
*
* see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object obj) {
if (obj instanceof Point) {
Point p = (Point) obj;
return equals(p);
}
return false;
}
// TODO Implement Point.euclidDist
/**
*
* param p return Euclidean distance of this point to point p
*/
public double euclidDist(Point p) {
// System.out.println(\"euclidDist not implemented yet\");
double X = this.getY() - p.getY();
double Y = this.getX() - p.getX();
double result = Math.sqrt(X * X + Y * Y);
return result;
}
/**
* param args: no args
*/
public static void main(String[] args) {
// test all methods
if (debug)
System.out.println(\"debug ON\");
else
System.out.println(\"debug OFF\");
System.out.println(\"EPSILON: \" + Point.EPSILON);
Point origin = new Point();
Point p1 = new Point(0.0, 4.0);
Point p2 = new Point(3.0000001, 3.9999999);
Point p3 = new Point(3.0, 4.0);
Point p4 = new Point(0.0, 5.0);
Point p5 = new Point(12.0, 0.0);
System.out.println(\"origin: \" + origin);
System.out.println(\"p1: \" + p1);
System.out.println(\"p2: \" + p2);
System.out.println(\"p3: \" + p3);
System.out.println(\"p4: \" + p4);
System.out.println(\"p5: \" + p5);
if (p2.equals(p3))
System.out.println(p2 + \" equals \" + p3);
else
System.out.println(p2 +.
fraction_math.c for Project 5 Program Design fraction.pdfanjanadistribution
/*fraction_math.c for Project 5
* Program Design
*/
//fraction_math.c
#include
#include
//function prototypes
void reduce(int numerator, int denominator, int*reduced_numerator, int*reduced_denominator);
int find_gcd(int m, int n);
//main function
int main(void)
{
int num1, denom1, num2, denom2, result_num, result_denom;
char operatorSymbol;
printf(\"Enter two fractions separated by a +, -, * or / sign: \");
scanf(\"%d/%d %c%d/%d\", &num1, &denom1, &operatorSymbol, &num2, &denom2);
switch (operatorSymbol)
{
case \'+\':
result_num = num1 * denom2 + num2 * denom1;
result_denom = denom1 * denom2;
//calling reduce function
reduce(result_num,result_denom,&result_num,&result_denom);
printf(\"The sum is %d/%d\ \", result_num, result_denom);
break;
case \'-\':
result_num = num1 * denom2 - num2 * denom1;
result_denom = denom1 * denom2;
//calling reduce function
reduce(result_num,result_denom,&result_num,&result_denom);
printf(\"The difference is %d/%d\ \", result_num, result_denom);
break;
case \'*\':
result_num = num1 * num2;
result_denom = denom1 * denom2;
//calling reduce function
reduce(result_num,result_denom,&result_num,&result_denom);
printf(\"The product is %d/%d\ \", result_num, result_denom);
break;
case \'/\':
result_num = num1 * denom2;
result_denom = denom1 * num2;
//calling reduce function
reduce(result_num,result_denom,&result_num,&result_denom);
printf(\"The quotient is %d/%d\ \", result_num, result_denom);
break;
default:
printf(\"Unrecognized operator: %c\ \", operatorSymbol);
}
getch();
return 0;
}
/*
The function reduce takes numberator and denominator and two pointers
and reduct the fraction by gcd
*/
void reduce(int numerator, int denominator, int*reduced_numerator, int*reduced_denominator)
{
//call find_gcd
int gcd=find_gcd(numerator,denominator);
//divide the value by gcd and set value at the pointer address
*reduced_numerator=numerator/gcd;
*reduced_denominator=denominator/gcd;
}
/*
The function find_gcd that takes m and n and returns
the gcd of two numbers
*/
int find_gcd(int m, int n)
{
if(n == 0)
return m;
return find_gcd(n, m%n);
}
----------------------------------------------------------------------------------
Sample output:
Enter two fractions separated by a +, -, * or / sign: 4/9-1/9
The difference is 1/3
Solution
/*fraction_math.c for Project 5
* Program Design
*/
//fraction_math.c
#include
#include
//function prototypes
void reduce(int numerator, int denominator, int*reduced_numerator, int*reduced_denominator);
int find_gcd(int m, int n);
//main function
int main(void)
{
int num1, denom1, num2, denom2, result_num, result_denom;
char operatorSymbol;
printf(\"Enter two fractions separated by a +, -, * or / sign: \");
scanf(\"%d/%d %c%d/%d\", &num1, &denom1, &operatorSymbol, &num2, &denom2);
switch (operatorSymbol)
{
case \'+\':
result_num = num1 * denom2 + num2 * denom1;
result_denom = denom1 * denom2;
//calling reduce function
reduce(result_num,result_denom,&result_num,&result_denom);
printf(\"The sum is %d/%d\ \", re.
Please read the comment ins codeExpressionTree.java-------------.pdfshanki7
Please read the comment ins code
ExpressionTree.java
----------------------------------
/**
* This is the class for Expression Tree.
* Used to create Expression Tree and Evaluate it
*/
/**
* Following logic is used to construct a Tree
* Here we use stack for Preparing Tree
* Loop through given Expression String
* If Character is Operand , Create node and push to stack
* If Character is Operator then
* 1)Create Node for Operator
* 2)Pop 2 nodes from Stack and Made
* OpretorNode--> left == first node pop
* OpretorNode--> right == second node pop
* At the end of creation of Expression Tree, Stack have only one node , which is root of
Expression tree
*/
/** Class ExpressionTree **/
class ExpressionTree
{
/** class TreeNode
* Stored Character ==> Digit(0..9) or a Operator +,-,*,/
* Left Node and Right Node
*
* **/
class TreeNode
{
char data;
TreeNode left, right;
/** constructor **/
public TreeNode(char data)
{
this.data = data;
this.left = null;
this.right = null;
}
}
/** class StackNode **/
class StackNode
{
TreeNode treeNode;
StackNode next;
/** constructor **/
public StackNode(TreeNode treeNode)
{
this.treeNode = treeNode;
next = null;
}
}
private static StackNode top;
/** constructor
* Constructor takes input string like \"+-+7*935*82*625\"
* Input should be in Prefix notation
* **/
public ExpressionTree(String expression)
{
top = null;
//Call Method for prepare expression tree
buildTree(expression);
}
/** function to clear tree **/
public void clear()
{
top = null;
}
/** function to push a node **/
private void push(TreeNode ptr)
{
if (top == null)
top = new StackNode(ptr);
else
{
StackNode nptr = new StackNode(ptr);
nptr.next = top;
top = nptr;
}
}
/** function to pop a node
* When it find operator pop 2 elements from Stack
*
* **/
private TreeNode pop()
{
if (top == null)
throw new RuntimeException(\"Underflow\");
else
{
TreeNode ptr = top.treeNode;
top = top.next;
return ptr;
}
}
/** function to get top node **/
private TreeNode peek()
{
return top.treeNode;
}
/** function to insert character **/
private void insert(char val)
{
try
{
//If Operand , Create node and push to Stack
if (isDigit(val))
{
TreeNode nptr = new TreeNode(val);
push(nptr);
}
//If Operator , Create node and popup 2 elements and make them its right and left
else if (isOperator(val))
{
TreeNode nptr = new TreeNode(val);
nptr.left = pop();
nptr.right = pop();
push(nptr);
}
}
catch (Exception e)
{
System.out.println(\"Invalid Expression\");
}
}
/** function to check if digit **/
private boolean isDigit(char ch)
{
return ch >= \'0\' && ch <= \'9\';
}
/** function to check if operator **/
private boolean isOperator(char ch)
{
return ch == \'+\' || ch == \'-\' || ch == \'*\' || ch == \'/\';
}
/** function to convert character to digit **/
private int toDigit(char ch)
{
return ch - \'0\';
}
/** function to build tree from input */
public void buildTree(String eqn)
{
for (int i = eqn.length() - 1; i >= 0; i--)
insert(eqn.charAt(i));
}
/** function to evaluate tree */
public dou.
write the To Dos to get the exact outputNOte A valid Fraction .pdfjyothimuppasani1
write the To Do\'s to get the exact output:
NOte: A valid Fraction number has a non-negative numerator and a positive denominator.
Default constructor initializes the object to safe empty state (an object with denom equals -1).
The two-argument constructor also validates the parameters and sets the object to the safe empty
state if the parameters are not valid.
Write the definitions and prototypes of following functions in Fraction.cpp and Fraction.h
respectively (They are indicated in the files by //TODO tag):
Define isEmpty function as a member function, which returns true if the object is in safe empty
state (an object is in the safe empty state if denominator (denom) equals -1).
Define display function, which sends a Fraction number to the output stream (with the
“Numerator/denominator” format). This function just prints \"Invalid Fraction Object!\" in the
screen if the object is in the safe empty state. In case that object denominator equals 1, it just
print the numerator.
Define the operator functions for the following operators:
“+=”, “+”, “*”
The overload of the above operators should make the following code possible:
The member operator+ : Adds two Fraction numbers and returns a Fraction number as the result.
This function returns an object with the safe empty state if either of Fraction numbers (operands)
is in safe empty state. It makes following code possible:
A+B ( where A and B are Fraction objects)
The member operator+= : Adds two Fraction numbers and assigns the result to the left operand,
then returns a reference to the left operand. If either of Fraction numbers (operands) is in safe
empty state, it initializes the left operand to the safe empty state, then returns a reference to the
left operand. It makes following code possible:
A+=B ( where A and B are Fraction objects)
The member operator* : Multiplies two Fraction numbers and returns a Fraction number as the
result. This function returns an object with the safe empty state if either of Fraction numbers
(operands) is in safe empty state. It makes following code possible:
A*B ( where A and B are Fraction objects)
fraction.cpp
#include \"Fraction.h\"
using namespace std;
namespace sict{
Fraction::Fraction(){
denom =-1; // safe empty state
}
Fraction::Fraction(int n, int d) // n: numerator, d: denominator
{
if(n >= 0 && d > 0){
num = n;
denom = d;
reduce();
}
else
denom =-1; // set to safe empty state
}
int Fraction::gcd() // returns the greatest common divisor of num and
denom
{
int mn = min(); // min of num and denom
int mx = max(); // mX of num and denom
for (int x=mn ; x > 0 ; x--) // find the greatest common divisor
if( mx % x == 0 && mn % x == 0)
return x;
return 1;
}
void Fraction::reduce() // simplify the Fraction number
{
int tmp = gcd();
num /= tmp;
denom /= tmp;
}
int Fraction::max ()
{
return (num >= denom) ? num : denom;
}
int Fraction::min()
{
return (num >= denom) ? denom : num;
}
// in_lab
// TODO: write the implementation of display function HERE
// TODO: w.
Please do Part A, Ill be really gratefulThe main.c is the skeleto.pdfaioils
Please do Part A, I'll be really grateful
The main.c is the skeleton code, the content of main.c is given below:
#include
#include
/* a rtpkt is the packet sent from one router to
another*/
struct rtpkt {
int sourceid; /* id of sending router sending this pkt */
int destid; /* id of router to which pkt being sent
(must be an directly connected neighbor) */
int *mincost; /* min cost to all the node */
};
struct distance_table
{
int **costs; // the distance table of curr_node, costs[i][j] is the cost from node i to node j
};
/*****************************************************************
***************** NETWORK EMULATION CODE STARTS BELOW ***********
The code below emulates the layer 2 and below network environment:
- emulates the transmission and delivery (with no loss and no
corruption) between two physically connected nodes
- calls the initializations routine rtinit once before
beginning emulation for each node.
You should read and understand the code below. For Part A, you should fill all parts with
annotation starting with "Todo". For Part B and Part C, you need to add additional routines for
their features.
******************************************************************/
struct event {
float evtime; /* event time */
int evtype; /* event type code */
int eventity; /* entity (node) where event occurs */
struct rtpkt *rtpktptr; /* ptr to packet (if any) assoc w/ this event */
struct event *prev;
struct event *next;
};
struct event *evlist = NULL; /* the event list */
struct distance_table *dts;
int **link_costs; /*This is a 2D matrix stroing the content defined in topo file*/
int num_nodes;
/* possible events: */
/*Note in this lab, we only have one event, namely FROM_LAYER2.It refer to that the packet
will pop out from layer3, you can add more event to emulate other activity for other layers. Like
FROM_LAYER3*/
#define FROM_LAYER2 1
float clocktime = 0.000;
/********************* EVENT HANDLINE ROUTINES *******/
/* The next set of routines handle the event list */
/*****************************************************/
void rtinit(struct distance_table *dt, int node, int *link_costs, int num_nodes)
{
/* Todo: Please write the code here*/
}
void rtupdate(struct distance_table *dt, struct rtpkt recv_pkt)
{
/* Todo: Please write the code here*/
}
void main(int argc, char *argv[])
{
struct event *eventptr;
/* Todo: Please write the code here to process the input.
Given different flag, you have different number of input for part A, B, C.
Please write your own code to parse the input for each part.
Specifically, in part A you need parse the input file and get num_nodes,
and fill in the content of dts and link_costs */
dts = (struct distance_table *) malloc(num_nodes * sizeof(struct distance_table));
link_costs = (int **) malloc(num_nodes * sizeof(int *));
for (int i = 0; i < num_nodes; i++)
{
link_costs[i] = (int *)malloc(num_nodes * sizeof(int));
}
for (int i = 0; i < num_nodes; i++)
{
rtinit(&dts[i], i, link_costs[i], num_nodes);
}
whil.
can someone fix the errors in this code- the name needs to be Fraction.pdfvinaythemodel
can someone fix the errors in this code? the name needs to be FractionDemo.java
//author: Jazmine Tapia
//date: 20 February 2023
//file: FractionDemo.java
/*
Lab 13 will also be using demonstation the
the multiplication of two factors.
*/
//import statements for Scanner class
import java.util.Scanner;
// Define a public class called Fraction
public class FractionDemo
{
// Define private instance variables for the numerator and denominator
private int numerator;
private int denominator;
// Define a constructor for the Fraction class that takes a numerator and denominator as
arguments
public FractionDemo(int numerator, int denominator)
{
// Set the denominator using the setDenominator() method defined below
setDenominator(denominator);
// Set the numerator
this.numerator = numerator;
// Reduce the fraction
reduce();
// Adjust the signs of the numerator and denominator if necessary
adjustSigns();
}
// Define a getter method for the numerator
public int getNumerator()
{
return numerator;
}
// Define a setter method for the numerator
public void setNumerator(int numerator)
{
this.numerator = numerator;
}
// Define a getter method for the denominator
public int getDenominator()
{
return denominator;
}
// Define a setter method for the denominator
public void setDenominator(int denominator)
{
// Set the denominator using the setDenominator() method defined below
setDenominator(denominator);
// Reduce the fraction
reduce();
// Adjust the signs of the numerator and denominator if necessary
adjustSigns();
}
// Define a private method to set the denominator
private void setDenominator(int denominator)
{
// If the denominator is zero, throw an exception
if (denominator == 0)
{
throw new IllegalArgumentException("Denominator cannot be zero");
}
// Set the denominator
this.denominator = denominator;
}
// Define a private method to calculate the greatest common divisor of two integers
private int gcd(int a, int b)
{
if (b == 0)
{
return a;
} else {
return gcd(b, a % b);
}
}
// Define a public method to reduce the fraction
public void reduce()
{
// Calculate the greatest common divisor of the numerator and denominator
int gcd = gcd(numerator, denominator);
// Divide both the numerator and denominator by the greatest common divisor to reduce the
fraction
numerator /= gcd;
denominator /= gcd;
}
// Define a private method to adjust the signs of the numerator and denominator if necessary
private void adjustSigns()
{
// If the denominator is negative, multiply both the numerator and denominator by -1 to adjust
the signs
if (denominator < 0)
{
numerator *= -1;
denominator *= -1;
}
}
// Define a public method to add two fractions
public FractionDemo add(FractionDemo other)
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
// Get the numerator and denominator for the first fraction
System.out.print("Enter the numerator of the first fraction: ");
int num1 = input.nextInt();
System.out.print("Enter the denominator of the first fraction.
Here is the code with comments to solve the question. Please do rate.pdfangelfragranc
Here is the code with comments to solve the question. Please do rate the answer if it helped.
Thank you very much.
Fraction.java
class Fraction
{
private int numerator; //where store the fraction datas
private int denominator;
//data members to store the reduced form of the fraction
//For ex: 6/3 can be stored in reduced form as 2/1.
//How to calculate the reduced form? We need the GCD of the 2 numbers and divide both
numerator and denominator
// by that GCD to give the reduced form
// for ex: 12/8 the GCD for 12 and 8 is 4 . so the numerator in reduced form is 12/4=3
//and denominator of reduced form is 8/4 = 2. So the reduced form of the fracton is 3/2
//GCD stands for greatest common divisor i.e the largest integer less than or equal to the 2
numbers
//which divides the numbers such that their remainder is 0
private int reducedNumerator;
private int reducedDenominator;
public Fraction(){ //default constructure
this(0,1);
}
public Fraction(int num, int denom){ //initialize the fraction
numerator = num;
denominator = denom;
computeReducedForm();
}
private void computeReducedForm()
{
//calculate the reduced form of the fraction
int gcd=GCD(); //compute gcd
reducedNumerator=numerator /gcd;
reducedDenominator=denominator/gcd;
}
//compares the reduced forms of the 2 fractions and returns true if they are equal and false
otherwise
public boolean equals(Fraction other){
return (reducedNumerator==other.reducedNumerator &&
reducedDenominator==other.reducedDenominator); //both numerator and denominator
should match
}
public void setNumerator(int num){
numerator=num;
computeReducedForm();
}
public void setDenominator(int denom){
denominator=denom;
computeReducedForm();
}
public int getNumerator(){
return numerator;
}
public int getDenominator(){
return denominator;
}
public String toString()
{
return reducedNumerator+\"/\"+reducedDenominator;
}
private int GCD()
{
int gcd=1;
for(int i=1;i<=numerator && i<=denominator;i++)
{
if(numerator % i ==0 && denominator % i==0) //should divide both with 0 remainder
gcd=i;
}
return gcd;
}
}
FractionCounter.java
public class FractionCounter
{
private Fraction theFraction;
private int counter;
public FractionCounter(Fraction frac) {
theFraction=frac;
counter=1;
}
public Fraction getFraction()
{
return theFraction;
}
public void incrementCount()
{
counter++;
}
public int getCount()
{
return counter;
}
public boolean compareFraction(Fraction other)
{
return theFraction.equals(other);
}
public String toString()
{
return theFraction+\" has a count of \"+counter;
}
}
Driver.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Driver {
public static void main(String[] args) {
Scanner scanner;
try {
scanner = new Scanner(new File(\"fractions.txt\"));
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
return;
}
String line,nums[];
int numerator,denominator;
Fraction fraction;
ArrayList countersList=new ArrayList(); //a list o.
C# Program. Create a Windows application that has the functionality .pdffathimalinks
C# Program. Create a Windows application that has the functionality of a calculator and works
with integral values. Allow the user to select buttons representing numeric values. If the user
attempts to divide by zero, throw and handle an exception.
Solution
below is the code from the windows application in visual studio:
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace SimpleCalculator
{
public partial class frmCalculator : Form
{
string operand1 = string.Empty;
string operand2 = string.Empty;
string result;
char operation;
public frmCalculator()
{
InitializeComponent();
}
private void frmCalculator_Load(object sender, EventArgs e)
{
btnOne.Click += new EventHandler(btn_Click);
btnTwo.Click += new EventHandler(btn_Click);
btnThree.Click += new EventHandler(btn_Click);
btnFour.Click += new EventHandler(btn_Click);
btnFive.Click += new EventHandler(btn_Click);
btnSix.Click += new EventHandler(btn_Click);
btnSeven.Click += new EventHandler(btn_Click);
btnEight.Click += new EventHandler(btn_Click);
btnNine.Click += new EventHandler(btn_Click);
btnZero.Click += new EventHandler(btn_Click);
btnDot.Click += new EventHandler(btn_Click);
}
void btn_Click(object sender, EventArgs e)
{
try
{
Button btn = sender as Button;
switch (btn.Name)
{
case \"btnOne\":
txtInput.Text += \"1\";
break;
case \"btnTwo\":
txtInput.Text += \"2\";
break;
case \"btnThree\":
txtInput.Text += \"3\";
break;
case \"btnFour\":
txtInput.Text += \"4\";
break;
case \"btnFive\":
txtInput.Text += \"5\";
break;
case \"btnSix\":
txtInput.Text += \"6\";
break;
case \"btnSeven\":
txtInput.Text += \"7\";
break;
case \"btnEight\":
txtInput.Text += \"8\";
break;
case \"btnNine\":
txtInput.Text += \"9\";
break;
case \"btnZero\":
txtInput.Text += \"0\";
break;
case \"btnDot\":
if(!txtInput.Text.Contains(\".\"))
txtInput.Text += \".\";
break;
}
}
catch(Exception ex)
{
MessageBox.Show(\"Sorry for the inconvenience, Unexpected error occured. Details:
\" +
ex.Message);
}
}
private void txtInput_KeyPress(object sender, KeyPressEventArgs e)
{
switch (e.KeyChar)
{
case \'1\':
case \'2\':
case \'3\':
case \'4\':
case \'5\':
case \'6\':
case \'7\':
case \'8\':
case \'9\':
case \'0\':
//case \'+\':
//case \'-\':
//case \'*\':
//case \'/\':
//case \'.\':
break;
default:
e.Handled = true;
MessageBox.Show(\"Only numbers, +, -, ., *, / are allowed\");
break;
}
}
private void txtInput_TextChanged(object sender, EventArgs e)
{
}
private void btnPlus_Click(object sender, EventArgs e)
{
operand1 = txtInput.Text;
operation = \'+\';
txtInput.Text = string.Empty;
}
private void btnMinus_Click(object sender, EventArgs e)
{
operand1 = txtInput.Text;
operation = \'-\';
txtInput.Text = string.Empty;
}
private void btnMulitply_Click(object sender, EventArgs e)
{
operand1 = txtInput.Text;
operation = \'*\';
txtInput.Text = string.Empty;
}
private void btnDivide_Click.
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxamrit47
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY GOOD WORK NICE FORMULA OR SOMETHING LIKE THAT, BUT ACTULLY HE CAN USE. THANK YOU.
Hartleys Function Code
Contains unread posts
Actions for Hartleys Function Code
Chad Hartley posted Nov 5, 2015 5:10 PM
Subscribe
This program will add an integer number and a decimal number up to 2 decimal places. I have included notes in the code to explain what each thing does. I hope I did this right. It compiles successfully.
PseudoCode
Start
Declare int O1; Stands for Output1
O1=sum; Sum is the functions name
Int sum()
Declare variables
Int num1;
Float num2;
Write “Enter a number.”
Scanf num1
Write”Enter a decimal number.”
Scanf num2
Return num1+num2
end
C Code
#include <stdio.h>
int sum();//prototype
int main()//calling program
{
//Declare a varaiable
int O1;
O1=sum();//main is calling sum one time.
//if I listed this twice it would run the function 'sum' twice.
// Example: if I add a new int (int O1, O2) and declare O2 to
//be O2=sum then the function would run twice.
}
int sum ()//function 'sum'
{
int num1;// Declare intergers/variables
float num2;
printf("Enter a number.\n");
scanf("%d",&num1);// Take first input and assign it to num1
printf("Enter a decimal number.\n");
scanf("%.2f",&num2);
//Can use the printf statement but when you are calling an integer you can use the return.
//printf("The sum of %d, %d, is %d", num1,num2,num1+num2);
return num1+num2;
}
ADD COMMENT HERE
Chaotic Function
Contains unread posts
Actions for Chaotic Function
Joshua Ray posted Nov 5, 2015 2:33 PM
Subscribe
float tmp
int i
function float chaos(float num)
{
for i < 20
num = 3.9*num*(1-num)
print num
}
main
print "Program description"
print "Request input btw 0 and 1"
tmp = input
chaos(tmp)
/*
* File: main.c
* Author: JaiEllRei
*
* Created on November 5, 2015, 2:04 PM
*/
#include <stdio.h>
#include <stdlib.h>
float chaos(float num);
int main(void)
{
float tmp;
printf("This program illustrates a choatic function. \n");
printf("Input a number between 0 and 1: ");
scanf("%f", &tmp);
chaos(tmp);
}
float chaos(float num)
{
for (int i=0; i<20; i++){
/*Chaotic Formula*/
num = 3.9 * num * (1-num);
printf("%.3f \n", num);
}
}
This program illustrates a choatic function.
Input a number between 0 and 1: .2
0.624
0.915
0.303
0.824
0.566
0.958
0.156
0.514
0.974
0.098
0.345
0.881
0.409
0.943
0.210
0.647
0.891
0.379
0.918
0.293
ADD COMMENT HERE
//MPH to KPH Conversion Function
Function KPHConv(value) as float
Set KPHConv = value*1.609344
End Function
Pseudocode for simple conversion program calling function
//Declare function
// MPH to KPH Conversion Function
Functio ...
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdfclimatecontrolsv
PROBLEM STATEMENT:
In this assignment, you will complete DoubleEndedList.java that implements the ListInterface as
well as an interface called DoubleEndedInterface which represents the list's entries by using a
chain of nodes that has both a head reference and a tail reference. Be sure to read through the
code and understand the implementation.
WHAT IS PROVIDED:
- A driver class to test your code. You should not modify this file!
- A list interface (ListInterface.java)
- A double ended interface (DoubleEndedInterface.java)
- An incomplete DoubleEndedList class (DoubleEndedList.java)
WHAT YOU NEED TO DO:
4. Complete the DoubleEndedList class
4. Run the driver and make sure your output is exactly the same as mine (at the bottom of
Driver.java)
\} // end else numberofEntries--; else throw new IndexOut0fBoundsException("Illegal position
given to remove operation."); return result; // Return removed entry }//endreturnreve public T
replace(int givenPosition, T newEntry) \{ T replace(int givenPosition, T newEntry) \{ if
((givenPosition >=1)&& (givenPosition <= numberOfEntries)) \{ // Assertion: The list is not
empty Node desiredNode = getNodeAt (givenPosition); ToriginalEntry = desiredNode.getData();
desiredNode.setData(newEntry); return originalEntry; f // end if else throw new
IndexOut0fBoundsException("Illegal position given to replace operation."); replace if ((
givenPosition >=1)&& (givenPosition <= number0fEntries)) \{ // Assertion: The list is not
empty Node desiredNode = getNodeAt ( givenPosition); T originalEntry = desiredNode.
getData( ); desiredNode.setData(newEntry); return originalentry; \} // end if throw new
Index0ut0fBoundsException("Illegal position given to replace operation."); \} // end replace
public T getEntry(int givenPosition) \{ if ((givenPosition >=1) \&\& (givenPosition < =
number0fEntries ) ) \{ // Assertion: The list is not empty return getNodeAt (givenPosition).
getData(); else // end if throw new IndexOut0fBoundsException("Illegal position given to
getEntry operation."); \} // end getEntry public boolean contains ( T anEntry) \{ boolean found =
false; Node currentNode = firstNode; while (!found && (currentNode != null)) \{ if
(anEntry.equals (currentNode.getData())) else found = true; \} // end while currentNode =
currentNode. getNextNode () ; return found; \} // end contains public int getLength() \{ return
numberofEntries; \} // end getLength public boolean isEmpty() \{ return number0fEntries ==0;
\} // end isEmpty public T[] toArray() \{ // The cast is safe because the new array contains null
entries aSuppressWarnings ("unchecked") T[] result =(T[]) new 0bject [numberofEntries]; //
Unchecked cast int index =0; Node currentNode = firstNode; while ((index < numberOfEntries)
\&\& (currentNode != null)) \& result [ index ]= currentNode. getData () ; currentNode =
currentNode.getNextNode ( ); index++; 3 // end while return result; 3 // end toArray // Returns a
reference to the node at a given position. // Precondition: L.
CSC-1106 Homework 09 (Class and static methods) Due Tuesday, Novembe.pdfmarketing413921
CSC-1106 Homework 09 (Class and static methods) Due: Tuesday, November 22, 2016 Write a
class encapsulating the concept of a rational number, a rational number has the following
attributes: an integer representing the numerator of the number. number, and another integer
representing the denominator of the rational The ratio should always be stored in its simplest
form. For example, the rational number 40/12 should be stored as 103. The class has the
following constructors and methods: A default constructor to set the Rational number to 0/1 A
constructor that has parameters for the numerator and denominator, and converts the resulting
ratio to simplified form simplify 0-a private method to convert the Rational number to simplified
form getGCD (x, y) -a private static method to return the largest common factor of the two
positive integers x and y (their greatest common divisor). For example, the greatest common
divisor of 40 and 12 is 4. value 0-returns the Rational number as a double value o-returns the
Rational number as a string in the form a/b toString multiply (Rational -a public method to return
the Rational number after multiplied by Rational number r add (Rational r)-a public method to
return the Rational number after addition with Rational number r floor (Rational r) -a public
method to return the integer of the floor of the Rational number. max (Rational x, Rational )-a
public static method to return the larger Rational number among x and y.
Solution
public class Rational {
/**
* A public constant that defines the rational value of 0.
*/
public static final Rational ZERO = new Rational(0, 1);
/**
* A public constant that defines the rational value of 1.
*/
public static final Rational ONE = new Rational(1, 1);
/**
* A public constant that defines the rational value of 0.5.
*/
public static final Rational HALF = new Rational(1, 2);
/*
* The Lowest and the Highest levels of precision allowed.
*/
private static final double LWST_PREC = 1E-3;
private static final double HIST_PREC = 1E-16;
private static double precision = 1E-10;
private final long num;
private final long den;
private final double result;
/**
* Creates a new {@code Rational} with the given numerator and
* denominator. It has special cases for Positive Infinity
* ({@link java.lang.Double#POSITIVE_INFINITY Double.POSITIVE_INFINITY}),
* Negative Infinity ({@link java.lang.Double#NEGATIVE_INFINITY
* Double.NEGATIVE_INFINITY}) and Not A Number
* ({@link java.lang.Double#NaN Double.NaN}.
*
* @param numerator The numerator.
* @param denominator The denominator.
*/
public Rational(long numerator, long denominator) {
// for dealing with \"infinities\" and \"NaN\":
if (denominator == 0) {
den = 0;
if (numerator > 0) {
num = 1;
result = Double.POSITIVE_INFINITY;
} else if (numerator < 0) {
num = -1;
result = Double.NEGATIVE_INFINITY;
} else {
num = 0;
result = Double.NaN;
}
return;
}
if (denominator < 0) {
numerator = 0L - numerator;
denominator = 0L - denominator;
}
num = numerator;.
1A. The acronym DBLC is used to name the Database Life Cycle.The DBL.pdfsutharbharat59
1A. The acronym DBLC is used to name the Database Life Cycle.The DBLC traces the history
of the databse system from its starting point to its obsolescence.The DBLC is composed of six
phases:initial study,design,inplementation and loading,testing and evaluation,operation and
maintenence and evolution.
2A.Centralized conceptual database design consists of typical simple databases and conducted by
single person or small team.
Decentralized conceptual database design consists of large number of entities and complex
relations and spread across multiple sites and developed by multiple teams.
Aggregation process requires designer to create single model in which various aggregation
problems must be addressed like synonyms and homonyms,entity and subtypes.
3A.The minimal data rule specifies that all the data defined in the data model are actually
required to fit to present and expected tuture data requirements.
4A.Top-down design by identifying the differnet entity types and definition to each entity
attributes. in other words top down design starts by defining the required data sets and defines
the data elements for each of those data sets.
Bottom up design first defiines the required attributes and theb groups the attributes to form
entities.
Refer the below diagram for third answer
Solution
1A. The acronym DBLC is used to name the Database Life Cycle.The DBLC traces the history
of the databse system from its starting point to its obsolescence.The DBLC is composed of six
phases:initial study,design,inplementation and loading,testing and evaluation,operation and
maintenence and evolution.
2A.Centralized conceptual database design consists of typical simple databases and conducted by
single person or small team.
Decentralized conceptual database design consists of large number of entities and complex
relations and spread across multiple sites and developed by multiple teams.
Aggregation process requires designer to create single model in which various aggregation
problems must be addressed like synonyms and homonyms,entity and subtypes.
3A.The minimal data rule specifies that all the data defined in the data model are actually
required to fit to present and expected tuture data requirements.
4A.Top-down design by identifying the differnet entity types and definition to each entity
attributes. in other words top down design starts by defining the required data sets and defines
the data elements for each of those data sets.
Bottom up design first defiines the required attributes and theb groups the attributes to form
entities.
Refer the below diagram for third answer.
More Related Content
Similar to Interfacepackage PJ1; public interface SimpleFractionInterface.pdf
public class Point { Insert your name here private dou.pdfanandshingavi23
public class Point {
/* Insert your name here */
private double x;
private double y;
public static final double EPSILON = 1e-5;
public static boolean debug = false;
// TODO Implement Point.Point(double x, double y)
/**
* instantiate a point \"this.x\" refers to the instance variable of the
* object x refers to the parameter same for this.y and y
*/
public Point(double x, double y) {
// System.out.println(\"Point(x,y) not implemented yet\");
this.x = x;
this.y = y;
}
// TODO Implement Point.Point()
/**
* Point() creates the origin by appropriately calling the general Point
* constructor
*/
public Point() {
// System.out.println(\"Point() not implemented yet\");
this.x = 0;
this.y = 0;
}
// TODO Implement Point.getX
/**
* return x
*/
public double getX() {
// System.out.println(\"getX not implemented yet\");
return this.x;
}
// TODO Implement Point.getY
/**
* return y
*/
public double getY() {
// System.out.println(\"getY not implemented yet\");
return this.y;
}
// Given Point.toString
/**
* convert to String
*/
public String toString() {
return \"(\" + x + \",\" + y + \")\";
}
// TODO Implement Point.equals
/**
*
* param p other point return test for equality using epsilon, because we
* are dealing with doubles,so roundoff can occur
*/
public boolean equals(Point p) {
// System.out.println(\"equals not implemented yet\");
if (p.getX() == this.getX() && p.getY() == this.getY())
return true;
else
return false;
}
// Given equals(Object o)
/**
* We need this equals method for ArrayList, because the generic
* ArrayList is really an ArrayList of Object. In the case of equals, the
* signature is public boolean equals(Object o) and the method below
* overrides the Object equals method and the calls the class\'s
* equals(Point) method
*
* see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object obj) {
if (obj instanceof Point) {
Point p = (Point) obj;
return equals(p);
}
return false;
}
// TODO Implement Point.euclidDist
/**
*
* param p return Euclidean distance of this point to point p
*/
public double euclidDist(Point p) {
// System.out.println(\"euclidDist not implemented yet\");
double X = this.getY() - p.getY();
double Y = this.getX() - p.getX();
double result = Math.sqrt(X * X + Y * Y);
return result;
}
/**
* param args: no args
*/
public static void main(String[] args) {
// test all methods
if (debug)
System.out.println(\"debug ON\");
else
System.out.println(\"debug OFF\");
System.out.println(\"EPSILON: \" + Point.EPSILON);
Point origin = new Point();
Point p1 = new Point(0.0, 4.0);
Point p2 = new Point(3.0000001, 3.9999999);
Point p3 = new Point(3.0, 4.0);
Point p4 = new Point(0.0, 5.0);
Point p5 = new Point(12.0, 0.0);
System.out.println(\"origin: \" + origin);
System.out.println(\"p1: \" + p1);
System.out.println(\"p2: \" + p2);
System.out.println(\"p3: \" + p3);
System.out.println(\"p4: \" + p4);
System.out.println(\"p5: \" + p5);
if (p2.equals(p3))
System.out.println(p2 + \" equals \" + p3);
else
System.out.println(p2 +.
fraction_math.c for Project 5 Program Design fraction.pdfanjanadistribution
/*fraction_math.c for Project 5
* Program Design
*/
//fraction_math.c
#include
#include
//function prototypes
void reduce(int numerator, int denominator, int*reduced_numerator, int*reduced_denominator);
int find_gcd(int m, int n);
//main function
int main(void)
{
int num1, denom1, num2, denom2, result_num, result_denom;
char operatorSymbol;
printf(\"Enter two fractions separated by a +, -, * or / sign: \");
scanf(\"%d/%d %c%d/%d\", &num1, &denom1, &operatorSymbol, &num2, &denom2);
switch (operatorSymbol)
{
case \'+\':
result_num = num1 * denom2 + num2 * denom1;
result_denom = denom1 * denom2;
//calling reduce function
reduce(result_num,result_denom,&result_num,&result_denom);
printf(\"The sum is %d/%d\ \", result_num, result_denom);
break;
case \'-\':
result_num = num1 * denom2 - num2 * denom1;
result_denom = denom1 * denom2;
//calling reduce function
reduce(result_num,result_denom,&result_num,&result_denom);
printf(\"The difference is %d/%d\ \", result_num, result_denom);
break;
case \'*\':
result_num = num1 * num2;
result_denom = denom1 * denom2;
//calling reduce function
reduce(result_num,result_denom,&result_num,&result_denom);
printf(\"The product is %d/%d\ \", result_num, result_denom);
break;
case \'/\':
result_num = num1 * denom2;
result_denom = denom1 * num2;
//calling reduce function
reduce(result_num,result_denom,&result_num,&result_denom);
printf(\"The quotient is %d/%d\ \", result_num, result_denom);
break;
default:
printf(\"Unrecognized operator: %c\ \", operatorSymbol);
}
getch();
return 0;
}
/*
The function reduce takes numberator and denominator and two pointers
and reduct the fraction by gcd
*/
void reduce(int numerator, int denominator, int*reduced_numerator, int*reduced_denominator)
{
//call find_gcd
int gcd=find_gcd(numerator,denominator);
//divide the value by gcd and set value at the pointer address
*reduced_numerator=numerator/gcd;
*reduced_denominator=denominator/gcd;
}
/*
The function find_gcd that takes m and n and returns
the gcd of two numbers
*/
int find_gcd(int m, int n)
{
if(n == 0)
return m;
return find_gcd(n, m%n);
}
----------------------------------------------------------------------------------
Sample output:
Enter two fractions separated by a +, -, * or / sign: 4/9-1/9
The difference is 1/3
Solution
/*fraction_math.c for Project 5
* Program Design
*/
//fraction_math.c
#include
#include
//function prototypes
void reduce(int numerator, int denominator, int*reduced_numerator, int*reduced_denominator);
int find_gcd(int m, int n);
//main function
int main(void)
{
int num1, denom1, num2, denom2, result_num, result_denom;
char operatorSymbol;
printf(\"Enter two fractions separated by a +, -, * or / sign: \");
scanf(\"%d/%d %c%d/%d\", &num1, &denom1, &operatorSymbol, &num2, &denom2);
switch (operatorSymbol)
{
case \'+\':
result_num = num1 * denom2 + num2 * denom1;
result_denom = denom1 * denom2;
//calling reduce function
reduce(result_num,result_denom,&result_num,&result_denom);
printf(\"The sum is %d/%d\ \", re.
Please read the comment ins codeExpressionTree.java-------------.pdfshanki7
Please read the comment ins code
ExpressionTree.java
----------------------------------
/**
* This is the class for Expression Tree.
* Used to create Expression Tree and Evaluate it
*/
/**
* Following logic is used to construct a Tree
* Here we use stack for Preparing Tree
* Loop through given Expression String
* If Character is Operand , Create node and push to stack
* If Character is Operator then
* 1)Create Node for Operator
* 2)Pop 2 nodes from Stack and Made
* OpretorNode--> left == first node pop
* OpretorNode--> right == second node pop
* At the end of creation of Expression Tree, Stack have only one node , which is root of
Expression tree
*/
/** Class ExpressionTree **/
class ExpressionTree
{
/** class TreeNode
* Stored Character ==> Digit(0..9) or a Operator +,-,*,/
* Left Node and Right Node
*
* **/
class TreeNode
{
char data;
TreeNode left, right;
/** constructor **/
public TreeNode(char data)
{
this.data = data;
this.left = null;
this.right = null;
}
}
/** class StackNode **/
class StackNode
{
TreeNode treeNode;
StackNode next;
/** constructor **/
public StackNode(TreeNode treeNode)
{
this.treeNode = treeNode;
next = null;
}
}
private static StackNode top;
/** constructor
* Constructor takes input string like \"+-+7*935*82*625\"
* Input should be in Prefix notation
* **/
public ExpressionTree(String expression)
{
top = null;
//Call Method for prepare expression tree
buildTree(expression);
}
/** function to clear tree **/
public void clear()
{
top = null;
}
/** function to push a node **/
private void push(TreeNode ptr)
{
if (top == null)
top = new StackNode(ptr);
else
{
StackNode nptr = new StackNode(ptr);
nptr.next = top;
top = nptr;
}
}
/** function to pop a node
* When it find operator pop 2 elements from Stack
*
* **/
private TreeNode pop()
{
if (top == null)
throw new RuntimeException(\"Underflow\");
else
{
TreeNode ptr = top.treeNode;
top = top.next;
return ptr;
}
}
/** function to get top node **/
private TreeNode peek()
{
return top.treeNode;
}
/** function to insert character **/
private void insert(char val)
{
try
{
//If Operand , Create node and push to Stack
if (isDigit(val))
{
TreeNode nptr = new TreeNode(val);
push(nptr);
}
//If Operator , Create node and popup 2 elements and make them its right and left
else if (isOperator(val))
{
TreeNode nptr = new TreeNode(val);
nptr.left = pop();
nptr.right = pop();
push(nptr);
}
}
catch (Exception e)
{
System.out.println(\"Invalid Expression\");
}
}
/** function to check if digit **/
private boolean isDigit(char ch)
{
return ch >= \'0\' && ch <= \'9\';
}
/** function to check if operator **/
private boolean isOperator(char ch)
{
return ch == \'+\' || ch == \'-\' || ch == \'*\' || ch == \'/\';
}
/** function to convert character to digit **/
private int toDigit(char ch)
{
return ch - \'0\';
}
/** function to build tree from input */
public void buildTree(String eqn)
{
for (int i = eqn.length() - 1; i >= 0; i--)
insert(eqn.charAt(i));
}
/** function to evaluate tree */
public dou.
write the To Dos to get the exact outputNOte A valid Fraction .pdfjyothimuppasani1
write the To Do\'s to get the exact output:
NOte: A valid Fraction number has a non-negative numerator and a positive denominator.
Default constructor initializes the object to safe empty state (an object with denom equals -1).
The two-argument constructor also validates the parameters and sets the object to the safe empty
state if the parameters are not valid.
Write the definitions and prototypes of following functions in Fraction.cpp and Fraction.h
respectively (They are indicated in the files by //TODO tag):
Define isEmpty function as a member function, which returns true if the object is in safe empty
state (an object is in the safe empty state if denominator (denom) equals -1).
Define display function, which sends a Fraction number to the output stream (with the
“Numerator/denominator” format). This function just prints \"Invalid Fraction Object!\" in the
screen if the object is in the safe empty state. In case that object denominator equals 1, it just
print the numerator.
Define the operator functions for the following operators:
“+=”, “+”, “*”
The overload of the above operators should make the following code possible:
The member operator+ : Adds two Fraction numbers and returns a Fraction number as the result.
This function returns an object with the safe empty state if either of Fraction numbers (operands)
is in safe empty state. It makes following code possible:
A+B ( where A and B are Fraction objects)
The member operator+= : Adds two Fraction numbers and assigns the result to the left operand,
then returns a reference to the left operand. If either of Fraction numbers (operands) is in safe
empty state, it initializes the left operand to the safe empty state, then returns a reference to the
left operand. It makes following code possible:
A+=B ( where A and B are Fraction objects)
The member operator* : Multiplies two Fraction numbers and returns a Fraction number as the
result. This function returns an object with the safe empty state if either of Fraction numbers
(operands) is in safe empty state. It makes following code possible:
A*B ( where A and B are Fraction objects)
fraction.cpp
#include \"Fraction.h\"
using namespace std;
namespace sict{
Fraction::Fraction(){
denom =-1; // safe empty state
}
Fraction::Fraction(int n, int d) // n: numerator, d: denominator
{
if(n >= 0 && d > 0){
num = n;
denom = d;
reduce();
}
else
denom =-1; // set to safe empty state
}
int Fraction::gcd() // returns the greatest common divisor of num and
denom
{
int mn = min(); // min of num and denom
int mx = max(); // mX of num and denom
for (int x=mn ; x > 0 ; x--) // find the greatest common divisor
if( mx % x == 0 && mn % x == 0)
return x;
return 1;
}
void Fraction::reduce() // simplify the Fraction number
{
int tmp = gcd();
num /= tmp;
denom /= tmp;
}
int Fraction::max ()
{
return (num >= denom) ? num : denom;
}
int Fraction::min()
{
return (num >= denom) ? denom : num;
}
// in_lab
// TODO: write the implementation of display function HERE
// TODO: w.
Please do Part A, Ill be really gratefulThe main.c is the skeleto.pdfaioils
Please do Part A, I'll be really grateful
The main.c is the skeleton code, the content of main.c is given below:
#include
#include
/* a rtpkt is the packet sent from one router to
another*/
struct rtpkt {
int sourceid; /* id of sending router sending this pkt */
int destid; /* id of router to which pkt being sent
(must be an directly connected neighbor) */
int *mincost; /* min cost to all the node */
};
struct distance_table
{
int **costs; // the distance table of curr_node, costs[i][j] is the cost from node i to node j
};
/*****************************************************************
***************** NETWORK EMULATION CODE STARTS BELOW ***********
The code below emulates the layer 2 and below network environment:
- emulates the transmission and delivery (with no loss and no
corruption) between two physically connected nodes
- calls the initializations routine rtinit once before
beginning emulation for each node.
You should read and understand the code below. For Part A, you should fill all parts with
annotation starting with "Todo". For Part B and Part C, you need to add additional routines for
their features.
******************************************************************/
struct event {
float evtime; /* event time */
int evtype; /* event type code */
int eventity; /* entity (node) where event occurs */
struct rtpkt *rtpktptr; /* ptr to packet (if any) assoc w/ this event */
struct event *prev;
struct event *next;
};
struct event *evlist = NULL; /* the event list */
struct distance_table *dts;
int **link_costs; /*This is a 2D matrix stroing the content defined in topo file*/
int num_nodes;
/* possible events: */
/*Note in this lab, we only have one event, namely FROM_LAYER2.It refer to that the packet
will pop out from layer3, you can add more event to emulate other activity for other layers. Like
FROM_LAYER3*/
#define FROM_LAYER2 1
float clocktime = 0.000;
/********************* EVENT HANDLINE ROUTINES *******/
/* The next set of routines handle the event list */
/*****************************************************/
void rtinit(struct distance_table *dt, int node, int *link_costs, int num_nodes)
{
/* Todo: Please write the code here*/
}
void rtupdate(struct distance_table *dt, struct rtpkt recv_pkt)
{
/* Todo: Please write the code here*/
}
void main(int argc, char *argv[])
{
struct event *eventptr;
/* Todo: Please write the code here to process the input.
Given different flag, you have different number of input for part A, B, C.
Please write your own code to parse the input for each part.
Specifically, in part A you need parse the input file and get num_nodes,
and fill in the content of dts and link_costs */
dts = (struct distance_table *) malloc(num_nodes * sizeof(struct distance_table));
link_costs = (int **) malloc(num_nodes * sizeof(int *));
for (int i = 0; i < num_nodes; i++)
{
link_costs[i] = (int *)malloc(num_nodes * sizeof(int));
}
for (int i = 0; i < num_nodes; i++)
{
rtinit(&dts[i], i, link_costs[i], num_nodes);
}
whil.
can someone fix the errors in this code- the name needs to be Fraction.pdfvinaythemodel
can someone fix the errors in this code? the name needs to be FractionDemo.java
//author: Jazmine Tapia
//date: 20 February 2023
//file: FractionDemo.java
/*
Lab 13 will also be using demonstation the
the multiplication of two factors.
*/
//import statements for Scanner class
import java.util.Scanner;
// Define a public class called Fraction
public class FractionDemo
{
// Define private instance variables for the numerator and denominator
private int numerator;
private int denominator;
// Define a constructor for the Fraction class that takes a numerator and denominator as
arguments
public FractionDemo(int numerator, int denominator)
{
// Set the denominator using the setDenominator() method defined below
setDenominator(denominator);
// Set the numerator
this.numerator = numerator;
// Reduce the fraction
reduce();
// Adjust the signs of the numerator and denominator if necessary
adjustSigns();
}
// Define a getter method for the numerator
public int getNumerator()
{
return numerator;
}
// Define a setter method for the numerator
public void setNumerator(int numerator)
{
this.numerator = numerator;
}
// Define a getter method for the denominator
public int getDenominator()
{
return denominator;
}
// Define a setter method for the denominator
public void setDenominator(int denominator)
{
// Set the denominator using the setDenominator() method defined below
setDenominator(denominator);
// Reduce the fraction
reduce();
// Adjust the signs of the numerator and denominator if necessary
adjustSigns();
}
// Define a private method to set the denominator
private void setDenominator(int denominator)
{
// If the denominator is zero, throw an exception
if (denominator == 0)
{
throw new IllegalArgumentException("Denominator cannot be zero");
}
// Set the denominator
this.denominator = denominator;
}
// Define a private method to calculate the greatest common divisor of two integers
private int gcd(int a, int b)
{
if (b == 0)
{
return a;
} else {
return gcd(b, a % b);
}
}
// Define a public method to reduce the fraction
public void reduce()
{
// Calculate the greatest common divisor of the numerator and denominator
int gcd = gcd(numerator, denominator);
// Divide both the numerator and denominator by the greatest common divisor to reduce the
fraction
numerator /= gcd;
denominator /= gcd;
}
// Define a private method to adjust the signs of the numerator and denominator if necessary
private void adjustSigns()
{
// If the denominator is negative, multiply both the numerator and denominator by -1 to adjust
the signs
if (denominator < 0)
{
numerator *= -1;
denominator *= -1;
}
}
// Define a public method to add two fractions
public FractionDemo add(FractionDemo other)
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
// Get the numerator and denominator for the first fraction
System.out.print("Enter the numerator of the first fraction: ");
int num1 = input.nextInt();
System.out.print("Enter the denominator of the first fraction.
Here is the code with comments to solve the question. Please do rate.pdfangelfragranc
Here is the code with comments to solve the question. Please do rate the answer if it helped.
Thank you very much.
Fraction.java
class Fraction
{
private int numerator; //where store the fraction datas
private int denominator;
//data members to store the reduced form of the fraction
//For ex: 6/3 can be stored in reduced form as 2/1.
//How to calculate the reduced form? We need the GCD of the 2 numbers and divide both
numerator and denominator
// by that GCD to give the reduced form
// for ex: 12/8 the GCD for 12 and 8 is 4 . so the numerator in reduced form is 12/4=3
//and denominator of reduced form is 8/4 = 2. So the reduced form of the fracton is 3/2
//GCD stands for greatest common divisor i.e the largest integer less than or equal to the 2
numbers
//which divides the numbers such that their remainder is 0
private int reducedNumerator;
private int reducedDenominator;
public Fraction(){ //default constructure
this(0,1);
}
public Fraction(int num, int denom){ //initialize the fraction
numerator = num;
denominator = denom;
computeReducedForm();
}
private void computeReducedForm()
{
//calculate the reduced form of the fraction
int gcd=GCD(); //compute gcd
reducedNumerator=numerator /gcd;
reducedDenominator=denominator/gcd;
}
//compares the reduced forms of the 2 fractions and returns true if they are equal and false
otherwise
public boolean equals(Fraction other){
return (reducedNumerator==other.reducedNumerator &&
reducedDenominator==other.reducedDenominator); //both numerator and denominator
should match
}
public void setNumerator(int num){
numerator=num;
computeReducedForm();
}
public void setDenominator(int denom){
denominator=denom;
computeReducedForm();
}
public int getNumerator(){
return numerator;
}
public int getDenominator(){
return denominator;
}
public String toString()
{
return reducedNumerator+\"/\"+reducedDenominator;
}
private int GCD()
{
int gcd=1;
for(int i=1;i<=numerator && i<=denominator;i++)
{
if(numerator % i ==0 && denominator % i==0) //should divide both with 0 remainder
gcd=i;
}
return gcd;
}
}
FractionCounter.java
public class FractionCounter
{
private Fraction theFraction;
private int counter;
public FractionCounter(Fraction frac) {
theFraction=frac;
counter=1;
}
public Fraction getFraction()
{
return theFraction;
}
public void incrementCount()
{
counter++;
}
public int getCount()
{
return counter;
}
public boolean compareFraction(Fraction other)
{
return theFraction.equals(other);
}
public String toString()
{
return theFraction+\" has a count of \"+counter;
}
}
Driver.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Driver {
public static void main(String[] args) {
Scanner scanner;
try {
scanner = new Scanner(new File(\"fractions.txt\"));
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
return;
}
String line,nums[];
int numerator,denominator;
Fraction fraction;
ArrayList countersList=new ArrayList(); //a list o.
C# Program. Create a Windows application that has the functionality .pdffathimalinks
C# Program. Create a Windows application that has the functionality of a calculator and works
with integral values. Allow the user to select buttons representing numeric values. If the user
attempts to divide by zero, throw and handle an exception.
Solution
below is the code from the windows application in visual studio:
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace SimpleCalculator
{
public partial class frmCalculator : Form
{
string operand1 = string.Empty;
string operand2 = string.Empty;
string result;
char operation;
public frmCalculator()
{
InitializeComponent();
}
private void frmCalculator_Load(object sender, EventArgs e)
{
btnOne.Click += new EventHandler(btn_Click);
btnTwo.Click += new EventHandler(btn_Click);
btnThree.Click += new EventHandler(btn_Click);
btnFour.Click += new EventHandler(btn_Click);
btnFive.Click += new EventHandler(btn_Click);
btnSix.Click += new EventHandler(btn_Click);
btnSeven.Click += new EventHandler(btn_Click);
btnEight.Click += new EventHandler(btn_Click);
btnNine.Click += new EventHandler(btn_Click);
btnZero.Click += new EventHandler(btn_Click);
btnDot.Click += new EventHandler(btn_Click);
}
void btn_Click(object sender, EventArgs e)
{
try
{
Button btn = sender as Button;
switch (btn.Name)
{
case \"btnOne\":
txtInput.Text += \"1\";
break;
case \"btnTwo\":
txtInput.Text += \"2\";
break;
case \"btnThree\":
txtInput.Text += \"3\";
break;
case \"btnFour\":
txtInput.Text += \"4\";
break;
case \"btnFive\":
txtInput.Text += \"5\";
break;
case \"btnSix\":
txtInput.Text += \"6\";
break;
case \"btnSeven\":
txtInput.Text += \"7\";
break;
case \"btnEight\":
txtInput.Text += \"8\";
break;
case \"btnNine\":
txtInput.Text += \"9\";
break;
case \"btnZero\":
txtInput.Text += \"0\";
break;
case \"btnDot\":
if(!txtInput.Text.Contains(\".\"))
txtInput.Text += \".\";
break;
}
}
catch(Exception ex)
{
MessageBox.Show(\"Sorry for the inconvenience, Unexpected error occured. Details:
\" +
ex.Message);
}
}
private void txtInput_KeyPress(object sender, KeyPressEventArgs e)
{
switch (e.KeyChar)
{
case \'1\':
case \'2\':
case \'3\':
case \'4\':
case \'5\':
case \'6\':
case \'7\':
case \'8\':
case \'9\':
case \'0\':
//case \'+\':
//case \'-\':
//case \'*\':
//case \'/\':
//case \'.\':
break;
default:
e.Handled = true;
MessageBox.Show(\"Only numbers, +, -, ., *, / are allowed\");
break;
}
}
private void txtInput_TextChanged(object sender, EventArgs e)
{
}
private void btnPlus_Click(object sender, EventArgs e)
{
operand1 = txtInput.Text;
operation = \'+\';
txtInput.Text = string.Empty;
}
private void btnMinus_Click(object sender, EventArgs e)
{
operand1 = txtInput.Text;
operation = \'-\';
txtInput.Text = string.Empty;
}
private void btnMulitply_Click(object sender, EventArgs e)
{
operand1 = txtInput.Text;
operation = \'*\';
txtInput.Text = string.Empty;
}
private void btnDivide_Click.
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxamrit47
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY GOOD WORK NICE FORMULA OR SOMETHING LIKE THAT, BUT ACTULLY HE CAN USE. THANK YOU.
Hartleys Function Code
Contains unread posts
Actions for Hartleys Function Code
Chad Hartley posted Nov 5, 2015 5:10 PM
Subscribe
This program will add an integer number and a decimal number up to 2 decimal places. I have included notes in the code to explain what each thing does. I hope I did this right. It compiles successfully.
PseudoCode
Start
Declare int O1; Stands for Output1
O1=sum; Sum is the functions name
Int sum()
Declare variables
Int num1;
Float num2;
Write “Enter a number.”
Scanf num1
Write”Enter a decimal number.”
Scanf num2
Return num1+num2
end
C Code
#include <stdio.h>
int sum();//prototype
int main()//calling program
{
//Declare a varaiable
int O1;
O1=sum();//main is calling sum one time.
//if I listed this twice it would run the function 'sum' twice.
// Example: if I add a new int (int O1, O2) and declare O2 to
//be O2=sum then the function would run twice.
}
int sum ()//function 'sum'
{
int num1;// Declare intergers/variables
float num2;
printf("Enter a number.\n");
scanf("%d",&num1);// Take first input and assign it to num1
printf("Enter a decimal number.\n");
scanf("%.2f",&num2);
//Can use the printf statement but when you are calling an integer you can use the return.
//printf("The sum of %d, %d, is %d", num1,num2,num1+num2);
return num1+num2;
}
ADD COMMENT HERE
Chaotic Function
Contains unread posts
Actions for Chaotic Function
Joshua Ray posted Nov 5, 2015 2:33 PM
Subscribe
float tmp
int i
function float chaos(float num)
{
for i < 20
num = 3.9*num*(1-num)
print num
}
main
print "Program description"
print "Request input btw 0 and 1"
tmp = input
chaos(tmp)
/*
* File: main.c
* Author: JaiEllRei
*
* Created on November 5, 2015, 2:04 PM
*/
#include <stdio.h>
#include <stdlib.h>
float chaos(float num);
int main(void)
{
float tmp;
printf("This program illustrates a choatic function. \n");
printf("Input a number between 0 and 1: ");
scanf("%f", &tmp);
chaos(tmp);
}
float chaos(float num)
{
for (int i=0; i<20; i++){
/*Chaotic Formula*/
num = 3.9 * num * (1-num);
printf("%.3f \n", num);
}
}
This program illustrates a choatic function.
Input a number between 0 and 1: .2
0.624
0.915
0.303
0.824
0.566
0.958
0.156
0.514
0.974
0.098
0.345
0.881
0.409
0.943
0.210
0.647
0.891
0.379
0.918
0.293
ADD COMMENT HERE
//MPH to KPH Conversion Function
Function KPHConv(value) as float
Set KPHConv = value*1.609344
End Function
Pseudocode for simple conversion program calling function
//Declare function
// MPH to KPH Conversion Function
Functio ...
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdfclimatecontrolsv
PROBLEM STATEMENT:
In this assignment, you will complete DoubleEndedList.java that implements the ListInterface as
well as an interface called DoubleEndedInterface which represents the list's entries by using a
chain of nodes that has both a head reference and a tail reference. Be sure to read through the
code and understand the implementation.
WHAT IS PROVIDED:
- A driver class to test your code. You should not modify this file!
- A list interface (ListInterface.java)
- A double ended interface (DoubleEndedInterface.java)
- An incomplete DoubleEndedList class (DoubleEndedList.java)
WHAT YOU NEED TO DO:
4. Complete the DoubleEndedList class
4. Run the driver and make sure your output is exactly the same as mine (at the bottom of
Driver.java)
\} // end else numberofEntries--; else throw new IndexOut0fBoundsException("Illegal position
given to remove operation."); return result; // Return removed entry }//endreturnreve public T
replace(int givenPosition, T newEntry) \{ T replace(int givenPosition, T newEntry) \{ if
((givenPosition >=1)&& (givenPosition <= numberOfEntries)) \{ // Assertion: The list is not
empty Node desiredNode = getNodeAt (givenPosition); ToriginalEntry = desiredNode.getData();
desiredNode.setData(newEntry); return originalEntry; f // end if else throw new
IndexOut0fBoundsException("Illegal position given to replace operation."); replace if ((
givenPosition >=1)&& (givenPosition <= number0fEntries)) \{ // Assertion: The list is not
empty Node desiredNode = getNodeAt ( givenPosition); T originalEntry = desiredNode.
getData( ); desiredNode.setData(newEntry); return originalentry; \} // end if throw new
Index0ut0fBoundsException("Illegal position given to replace operation."); \} // end replace
public T getEntry(int givenPosition) \{ if ((givenPosition >=1) \&\& (givenPosition < =
number0fEntries ) ) \{ // Assertion: The list is not empty return getNodeAt (givenPosition).
getData(); else // end if throw new IndexOut0fBoundsException("Illegal position given to
getEntry operation."); \} // end getEntry public boolean contains ( T anEntry) \{ boolean found =
false; Node currentNode = firstNode; while (!found && (currentNode != null)) \{ if
(anEntry.equals (currentNode.getData())) else found = true; \} // end while currentNode =
currentNode. getNextNode () ; return found; \} // end contains public int getLength() \{ return
numberofEntries; \} // end getLength public boolean isEmpty() \{ return number0fEntries ==0;
\} // end isEmpty public T[] toArray() \{ // The cast is safe because the new array contains null
entries aSuppressWarnings ("unchecked") T[] result =(T[]) new 0bject [numberofEntries]; //
Unchecked cast int index =0; Node currentNode = firstNode; while ((index < numberOfEntries)
\&\& (currentNode != null)) \& result [ index ]= currentNode. getData () ; currentNode =
currentNode.getNextNode ( ); index++; 3 // end while return result; 3 // end toArray // Returns a
reference to the node at a given position. // Precondition: L.
CSC-1106 Homework 09 (Class and static methods) Due Tuesday, Novembe.pdfmarketing413921
CSC-1106 Homework 09 (Class and static methods) Due: Tuesday, November 22, 2016 Write a
class encapsulating the concept of a rational number, a rational number has the following
attributes: an integer representing the numerator of the number. number, and another integer
representing the denominator of the rational The ratio should always be stored in its simplest
form. For example, the rational number 40/12 should be stored as 103. The class has the
following constructors and methods: A default constructor to set the Rational number to 0/1 A
constructor that has parameters for the numerator and denominator, and converts the resulting
ratio to simplified form simplify 0-a private method to convert the Rational number to simplified
form getGCD (x, y) -a private static method to return the largest common factor of the two
positive integers x and y (their greatest common divisor). For example, the greatest common
divisor of 40 and 12 is 4. value 0-returns the Rational number as a double value o-returns the
Rational number as a string in the form a/b toString multiply (Rational -a public method to return
the Rational number after multiplied by Rational number r add (Rational r)-a public method to
return the Rational number after addition with Rational number r floor (Rational r) -a public
method to return the integer of the floor of the Rational number. max (Rational x, Rational )-a
public static method to return the larger Rational number among x and y.
Solution
public class Rational {
/**
* A public constant that defines the rational value of 0.
*/
public static final Rational ZERO = new Rational(0, 1);
/**
* A public constant that defines the rational value of 1.
*/
public static final Rational ONE = new Rational(1, 1);
/**
* A public constant that defines the rational value of 0.5.
*/
public static final Rational HALF = new Rational(1, 2);
/*
* The Lowest and the Highest levels of precision allowed.
*/
private static final double LWST_PREC = 1E-3;
private static final double HIST_PREC = 1E-16;
private static double precision = 1E-10;
private final long num;
private final long den;
private final double result;
/**
* Creates a new {@code Rational} with the given numerator and
* denominator. It has special cases for Positive Infinity
* ({@link java.lang.Double#POSITIVE_INFINITY Double.POSITIVE_INFINITY}),
* Negative Infinity ({@link java.lang.Double#NEGATIVE_INFINITY
* Double.NEGATIVE_INFINITY}) and Not A Number
* ({@link java.lang.Double#NaN Double.NaN}.
*
* @param numerator The numerator.
* @param denominator The denominator.
*/
public Rational(long numerator, long denominator) {
// for dealing with \"infinities\" and \"NaN\":
if (denominator == 0) {
den = 0;
if (numerator > 0) {
num = 1;
result = Double.POSITIVE_INFINITY;
} else if (numerator < 0) {
num = -1;
result = Double.NEGATIVE_INFINITY;
} else {
num = 0;
result = Double.NaN;
}
return;
}
if (denominator < 0) {
numerator = 0L - numerator;
denominator = 0L - denominator;
}
num = numerator;.
1A. The acronym DBLC is used to name the Database Life Cycle.The DBL.pdfsutharbharat59
1A. The acronym DBLC is used to name the Database Life Cycle.The DBLC traces the history
of the databse system from its starting point to its obsolescence.The DBLC is composed of six
phases:initial study,design,inplementation and loading,testing and evaluation,operation and
maintenence and evolution.
2A.Centralized conceptual database design consists of typical simple databases and conducted by
single person or small team.
Decentralized conceptual database design consists of large number of entities and complex
relations and spread across multiple sites and developed by multiple teams.
Aggregation process requires designer to create single model in which various aggregation
problems must be addressed like synonyms and homonyms,entity and subtypes.
3A.The minimal data rule specifies that all the data defined in the data model are actually
required to fit to present and expected tuture data requirements.
4A.Top-down design by identifying the differnet entity types and definition to each entity
attributes. in other words top down design starts by defining the required data sets and defines
the data elements for each of those data sets.
Bottom up design first defiines the required attributes and theb groups the attributes to form
entities.
Refer the below diagram for third answer
Solution
1A. The acronym DBLC is used to name the Database Life Cycle.The DBLC traces the history
of the databse system from its starting point to its obsolescence.The DBLC is composed of six
phases:initial study,design,inplementation and loading,testing and evaluation,operation and
maintenence and evolution.
2A.Centralized conceptual database design consists of typical simple databases and conducted by
single person or small team.
Decentralized conceptual database design consists of large number of entities and complex
relations and spread across multiple sites and developed by multiple teams.
Aggregation process requires designer to create single model in which various aggregation
problems must be addressed like synonyms and homonyms,entity and subtypes.
3A.The minimal data rule specifies that all the data defined in the data model are actually
required to fit to present and expected tuture data requirements.
4A.Top-down design by identifying the differnet entity types and definition to each entity
attributes. in other words top down design starts by defining the required data sets and defines
the data elements for each of those data sets.
Bottom up design first defiines the required attributes and theb groups the attributes to form
entities.
Refer the below diagram for third answer.
In chemistry, hybridisation (or hybridization) is.pdfsutharbharat59
In chemistry, hybridisation (or hybridization) is the concept of mixing atomic
orbitals to form new hybrid orbitals suitable for the qualitative description of atomic bonding
properties. Hybridised orbitals are very useful in the explanation of the shape of molecular
orbitals for molecules. It is an integral part of valence bond theory. Although sometimes taught
together with the valence shell electron-pair repulsion (VSEPR) theory, valence bond and
hybridization are in fact not related to the VSEPR model.[1] Contents [hide] 1 Historical
development 2 Types of hybridisation 2.1 sp3 hybrids 2.2 sp2 hybrids 2.3 sp hybrids 3
Hybridisation and molecule shape 3.1 Explanation of the shape of water 3.2 Controversy
regarding d-orbital participation 4 Hybridisation theory vs. MO theory 5 See also 6 External
links 7 References [edit]Historical development Chemist Linus Pauling first developed the
hybridisation theory in order to explain the structure of molecules such as methane (CH4).[2]
This concept was developed for such simple chemical systems, but the approach was later
applied more widely, and today it is considered an effective heuristic for rationalizing the
structures of organic compounds. For quantitative calculations of electronic structure and
molecular properties, hybridisation theory is not as practical as molecular orbital theory.
Problems with hybridisation are especially notable when the d orbitals are involved in bonding,
as in coordination chemistry and organometallic chemistry. Although hybridisation schemes in
transition metal chemistry can be used, they are not generally as accurate. Orbitals are a model
representation of the behaviour of electrons within molecules. In the case of simple
hybridisation, this approximation is based on atomic orbitals, similar to those obtained for the
hydrogen atom, the only atom for which an exact analytic solution to its Schrödinger equation is
known. In heavier atoms, like carbon, nitrogen, and oxygen, the atomic orbitals used are the 2s
and 2p orbitals, similar to excited state orbitals for hydrogen. Hybridised orbitals are assumed to
be mixtures of these atomic orbitals, superimposed on each other in various proportions. The
theory of hybridisation is most applicable under these assumptions. It gives a simple orbital
picture equivalent to Lewis structures. Hybridisation is not required to describe molecules, but
for molecules made up from carbon, nitrogen and oxygen (and to a lesser extent, sulfur and
phosphorus) the hybridisation theory/model makes the description much easier. The
hybridisation theory finds its use mainly in organic chemistry. Its explanation starts with the way
bonding is organized in methane. [edit]Types of hybridisation [edit]sp3 hybrids Hybridisation
describes the bonding atoms from an atom\'s point of view. That is, for a tetrahedrally
coordinated carbon (e.g., methane, CH4), the carbon should have 4 orbitals with the correct
symmetry to bond to the 4 hydrogen atoms. The .
RPS 19 stands for ribosomal protein S19. This proteins is synthesise.pdfsutharbharat59
RPS 19 stands for ribosomal protein S19. This proteins is synthesised and located in the cytosol.
It is then transported to the respective destinations. RPS 19 to reach the mitochondria must cross
the 2 mitochondrial membranes the outer and inner membrane.
Solution
RPS 19 stands for ribosomal protein S19. This proteins is synthesised and located in the cytosol.
It is then transported to the respective destinations. RPS 19 to reach the mitochondria must cross
the 2 mitochondrial membranes the outer and inner membrane..
y^(iv)-4y=0taking 4y to RHS we gety^(iv) = 4yy^(iii) = integra.pdfsutharbharat59
y^(iv)-4y=0
taking 4y to RHS we get
y^(iv) = 4y
y^(iii) = integral of(4y)
=4
y^(ii) = integral of(4)
= 0+ A note:The integral of a constant C with respect to y is Cy+ A
y^(i) = integral of(A)
= 0 +A
y =(intgral of A)
=0+A
So the general solution is y= A(constant).
Solution
y^(iv)-4y=0
taking 4y to RHS we get
y^(iv) = 4y
y^(iii) = integral of(4y)
=4
y^(ii) = integral of(4)
= 0+ A note:The integral of a constant C with respect to y is Cy+ A
y^(i) = integral of(A)
= 0 +A
y =(intgral of A)
=0+A
So the general solution is y= A(constant)..
Fe(s) + Mn2+(aq) Fe2+(aq) + Mn(s)Yes this reaction is spon.pdfsutharbharat59
Fe(s) + Mn2+(aq) Fe2+(aq) + Mn(s)
Yes this reaction is spontaneous in the reverse direction
This is because E of the whole rection will be +ve in the reverse direction
We know that if E of the reaction is +ve, the reaction is Spontaneous
Solution
Fe(s) + Mn2+(aq) Fe2+(aq) + Mn(s)
Yes this reaction is spontaneous in the reverse direction
This is because E of the whole rection will be +ve in the reverse direction
We know that if E of the reaction is +ve, the reaction is Spontaneous.
When Na2SO3 is dissolved in water, Na+ and SO32- ions are formedN.pdfsutharbharat59
When Na2SO3 is dissolved in water, Na+ and SO32- ions are formed:
Na2SO3 => 2 Na+ + SO32-
The SO32- ions are weak bases and ionize in water to form HSO3- and OH- ions:
SO32- + H2O <=> HSO3- + OH-
Since OH- ions are formed, the pH will be greater than 7 and the solution is basic.
Solution
When Na2SO3 is dissolved in water, Na+ and SO32- ions are formed:
Na2SO3 => 2 Na+ + SO32-
The SO32- ions are weak bases and ionize in water to form HSO3- and OH- ions:
SO32- + H2O <=> HSO3- + OH-
Since OH- ions are formed, the pH will be greater than 7 and the solution is basic..
Therapsids is a group of synapsidsAdaptation1.Four limbs extent.pdfsutharbharat59
Therapsids is a group of synapsids
Adaptation:
1.Four limbs extent vertically in contrast to crawling limbs
2..Feet were more symmetrical
3.Jaws were more complexed and powerful
4.Frontal incisors canines for tearing.
Hadrocodium
They were primitive mammals
1.Advance features
2.Large brain
3.Advance ear
Prosimian
Group of primates,
primitive mammalians characters is bicornuate uterus
Solution
Therapsids is a group of synapsids
Adaptation:
1.Four limbs extent vertically in contrast to crawling limbs
2..Feet were more symmetrical
3.Jaws were more complexed and powerful
4.Frontal incisors canines for tearing.
Hadrocodium
They were primitive mammals
1.Advance features
2.Large brain
3.Advance ear
Prosimian
Group of primates,
primitive mammalians characters is bicornuate uterus.
They trade away higher fecundity for future reproduction.Being ite.pdfsutharbharat59
They trade away higher fecundity for future reproduction.
Being iteroparous, they can produce Offsprings throughout life, but they produce single
Offsprings trading away their fecundity so that they can reproduce throughout.
Solution
They trade away higher fecundity for future reproduction.
Being iteroparous, they can produce Offsprings throughout life, but they produce single
Offsprings trading away their fecundity so that they can reproduce throughout..
The statements that are consistent with facts known about membrane a.pdfsutharbharat59
The statements that are consistent with facts known about membrane are
1. Some transport processes use the energy of a second transport process to move species across
membranes.
2. Active transport always employs ATP hydrolysis to provide the energy for the transporter.
Solution
The statements that are consistent with facts known about membrane are
1. Some transport processes use the energy of a second transport process to move species across
membranes.
2. Active transport always employs ATP hydrolysis to provide the energy for the transporter..
The implementation algorithm whose amortized complexity is O (1) to .pdfsutharbharat59
The implementation algorithm whose amortized complexity is O (1) to implement queue using
two stacks is given as follows:
Algorithm for Enqueue:
Enqueue(element):
//Push the element in the stack 1.
S1.push(element)
Algorithm for Dequeue:
Dequeue():
//Check the condition that stack 2 is empty or not.
//If it is empty then execute do part otherwise go
//to the else part.
if S2.isEmpty() then
//Execute the while loop till the
//size of stack 1 is greater than 1.
while S1.size() > 1 do
//Pop the element from stack 1 and
// store it in the variable element.
element = S1.pop()
//And push the popped element
// of stack 1 to the stack 2.
S2.push(element)
//Pop the element form stack 1 and
//store it in the variable element.
element = S1.pop()
//Return the element.
return element
//The else part.
else
//Pop the element form stack 2 and
//store it in the variable element.
element = S2.pop()
//Return the element.
return element
Where, S1 and S2 represent stack 1 and stack 2 respectively.
Explanation:
1 + 1 + 1 + … + n
Thus, for the dequeue operation the amortized complexity is O (1).
Solution
The implementation algorithm whose amortized complexity is O (1) to implement queue using
two stacks is given as follows:
Algorithm for Enqueue:
Enqueue(element):
//Push the element in the stack 1.
S1.push(element)
Algorithm for Dequeue:
Dequeue():
//Check the condition that stack 2 is empty or not.
//If it is empty then execute do part otherwise go
//to the else part.
if S2.isEmpty() then
//Execute the while loop till the
//size of stack 1 is greater than 1.
while S1.size() > 1 do
//Pop the element from stack 1 and
// store it in the variable element.
element = S1.pop()
//And push the popped element
// of stack 1 to the stack 2.
S2.push(element)
//Pop the element form stack 1 and
//store it in the variable element.
element = S1.pop()
//Return the element.
return element
//The else part.
else
//Pop the element form stack 2 and
//store it in the variable element.
element = S2.pop()
//Return the element.
return element
Where, S1 and S2 represent stack 1 and stack 2 respectively.
Explanation:
1 + 1 + 1 + … + n
Thus, for the dequeue operation the amortized complexity is O (1)..
The correct matches are as discussed below(a) A (Glycoprotiens ar.pdfsutharbharat59
The correct matches are as discussed below:
(a) A (Glycoprotiens are complex proteins found on the outer layer of the plasma membrane and
form the structural component of surface receptors)
(b) A (The outer surface proteins such as glycoproteins can be easily separated from the plasma
membrane by mild treatments of salts)
(c) C (The proteins/biomolecules localized on the inner side of plasma membrane are tightly
bound to it and thus require harsh chemical treatments are required for their separation)
(d) D (A transmembrane protein which spans the whole width of the plasma membrane is
actively involved in transport of ions and materials across it)
(e) B (A ganglioside is a complex biomolecular lipid found on the periphery of the cell whose
branches are embedded in the membrane itself)
(f) D, E (Both, the transmembrane protein and the phospholipid of plasma membrane show flip-
flop action for transport of materials across it. This is owing to the dynamic physical state of the
plasma membrane)
Solution
The correct matches are as discussed below:
(a) A (Glycoprotiens are complex proteins found on the outer layer of the plasma membrane and
form the structural component of surface receptors)
(b) A (The outer surface proteins such as glycoproteins can be easily separated from the plasma
membrane by mild treatments of salts)
(c) C (The proteins/biomolecules localized on the inner side of plasma membrane are tightly
bound to it and thus require harsh chemical treatments are required for their separation)
(d) D (A transmembrane protein which spans the whole width of the plasma membrane is
actively involved in transport of ions and materials across it)
(e) B (A ganglioside is a complex biomolecular lipid found on the periphery of the cell whose
branches are embedded in the membrane itself)
(f) D, E (Both, the transmembrane protein and the phospholipid of plasma membrane show flip-
flop action for transport of materials across it. This is owing to the dynamic physical state of the
plasma membrane).
Step1 Moles of He = 504.0026Step2 Moles of Xe = 50131.29Step3 .pdfsutharbharat59
Step1 Moles of He = 50/4.0026
Step2 Moles of Xe = 50/131.29
Step3 Find total moles
Step4 Partial pressure of He=[ Moles of He/Total moles] x750 torr
Step5 Partial pressure of Xe = 750 - partial pressure of He
Solution
Step1 Moles of He = 50/4.0026
Step2 Moles of Xe = 50/131.29
Step3 Find total moles
Step4 Partial pressure of He=[ Moles of He/Total moles] x750 torr
Step5 Partial pressure of Xe = 750 - partial pressure of He.
SKIN SENSORY ORGANThe human skin is the external covering of the .pdfsutharbharat59
SKIN :SENSORY ORGAN
The human skin is the external covering of the body. In people, it is the biggest organ of the
integumentary framework. The skin has up to seven layers of ectodermal tissue and watches the
hidden muscles, bones, tendons and inside organs. Human skin is like that of most different
warm blooded creatures. Despite the fact that about all human skin is secured with hair follicles,
it can seem bald. There are two general sorts of skin, bristly and glabrous skin. The descriptive
word cutaneous truly signifies \"of the skin\" . Since it interfaces with the earth, skin assumes an
essential insusceptibility part in securing the body against pathogens[3] and over the top water
loss. Its different capacities are protection, temperature direction, sensation, blend of vitamin D,
and the insurance of vitamin B folates. Extremely harmed skin will attempt to recuperate by
framing scar tissue. This is frequently stained and depigmented. In people, skin pigmentation
shifts among populaces, and skin sort can go from dry to slick. Such skin assortment gives a rich
and various living space for microorganisms that number around 1000 species from 19 phyla,
exhibit on the human skin
Skin has mesodermal cells, pigmentation, for example, melanin gave by melanocytes, which
ingest a portion of the possibly risky bright radiation (UV) in daylight. It additionally contains
DNA repair compounds that switch UV harm, with the end goal that individuals without the
qualities for these chemicals endure high rates of skin malignancy. One shape prevalently
delivered by UV light, threatening melanoma, is especially intrusive, making it spread rapidly,
and can frequently be dangerous. Human skin pigmentation shifts among populaces in a striking
way. This has prompted to the order of people(s) on the premise of skin color. The skin is the
biggest organ in the human body. For the normal grown-up human, the skin has a surface zone of
between 1.5-2.0 square meters (16.1-21.5 sq ft.). The thickness of the skin shifts significantly
over all parts of the body, and amongst men and ladies and the youthful and the old. A case is the
skin on the lower arm which is all things considered 1.3 mm in the male and 1.26 mm in the
female. The normal square inch (6.5 cm²) of skin holds 650 sweat organs, 20 veins, 60,000
melanocytes, and more than 1,000 nerve endings. The normal human skin cell is around 30
micrometers in distance across, yet there are variations. A skin cell more often than not extends
from 25-40 micrometers (squared), contingent upon an assortment of variables. Skin is made out
of three essential layers: the epidermis, the dermis and the hypodermis .Epidermis, \"epi\"
originating from the Greek signifying \"over\" or \"upon\", is the peripheral layer of the skin. It
shapes the waterproof, defensive wrap over the body\'s surface which likewise serves as a
hindrance to disease and is comprised of stratified squamous epithelium with a hidden basal
lamina.
The epiderm.
a) FlaseIn terms of trasing volume it is by far the largest market.pdfsutharbharat59
a) Flase
In terms of trasing volume it is by far the largest market in the world
b) True
As home currency weakens, one has to pay more units of home currency to buy one unit of
foreign currency, hence making import costlier
Solution
a) Flase
In terms of trasing volume it is by far the largest market in the world
b) True
As home currency weakens, one has to pay more units of home currency to buy one unit of
foreign currency, hence making import costlier.
//tested on Eclipse
/*************Rainfall.java*************/
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class RainFall {
/*Data member variable*/
private double monthlyRainFall;
private double monthsRainFall[]=new double[12];
private int month=0;
private double maxRain=0.0;
private int maxrainMonth;
private double minRain=0.0;
private int minRainMonth;
/*creating map for storing month*/
Map monthMap=new HashMap();
Scanner input=new Scanner(System.in);
/*Initializing map with value while default constructor*/
public RainFall(){
monthMap.put(0, \"January\");
monthMap.put(1, \"February\");
monthMap.put(2, \"March\");
monthMap.put(3, \"April\");
monthMap.put(4, \"May\");
monthMap.put(5, \"June\");
monthMap.put(6, \"July\");
monthMap.put(7, \"August\");
monthMap.put(8, \"September\");
monthMap.put(9, \"October\");
monthMap.put(10, \"November\");
monthMap.put(11, \"December\");
}
/*Getting monthlyRainFall*/
public double getMonthlyRainFall() {
return monthlyRainFall;
}
/*Setting monthly rainfall If it is negative then it loops until positive */
public void setMonthlyRainFall(double monthlyRainFall) {
while(monthlyRainFall<0){
System.out.println(\"Please Enter positive value of monthly rainfall\");
monthlyRainFall=input.nextDouble();
}
monthsRainFall[month++]=monthlyRainFall;
}
/*Getting average month rain fall*/
public void averageMonthlyRainFall(){
double totalRainFall=0;
/*first calculate totalRain fall after that divide it total month*/
for(int i=0;imonthsRainFall[i]){
minRain=monthsRainFall[i];
minRainMonth=i;
}
}
System.out.println(\"Min Rain Month Fall: \"+monthMap.get(minRainMonth));
}
/*Main method start*/
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
/*Creating instance of rainFall class*/
RainFall rainFall=new RainFall();
/*getting rainfall for each month from user*/
for(int i=0;i<12;i++){
System.out.println(\"Please Enter rainFall for \"+(i+1)+\" Month\");
rainFall.setMonthlyRainFall(sc.nextDouble());
}
/*Average Monthly rainfall*/
rainFall.averageMonthlyRainFall();
/*Total Rain Fall in a year*/
rainFall.totalRainFall();
/*Max rainFall Month*/
rainFall.maxRainFallMonth();
/*Minimum rainFall Month*/
rainFall.minRainFallMonth();
sc.close();
}
}
/***************output************/
Please Enter rainFall for 1 Month
121
Please Enter rainFall for 2 Month
134
Please Enter rainFall for 3 Month
54
Please Enter rainFall for 4 Month
167
Please Enter rainFall for 5 Month
256
Please Enter rainFall for 6 Month
456
Please Enter rainFall for 7 Month
78
Please Enter rainFall for 8 Month
290
Please Enter rainFall for 9 Month
176
Please Enter rainFall for 10 Month
263
Please Enter rainFall for 11 Month
100
Please Enter rainFall for 12 Month
189
Average Monthly Rain Fall: 190.33
Total Rain Fall for the year: 2284
Max Rain Month Fall: June
Min Rain Month Fall: March
Thanks a lot. If you have any doubt. Please let me know
Solution
//tested on Eclipse
/********.
Ques-1Part-a Mitosis it is a somatic cell division in an organi.pdfsutharbharat59
Ques-1:
Part-a: Mitosis: it is a somatic cell division in an organism & this division is useful to maintain
body growth
Part-b: Meiosis: it is the reproductive reduction cell division & it is useful to produce gametes for
fertilization finally to generate a mature embryo
Part-c: cytokinesis: It is defined as the process of division of cytoplasm during cell division
either in mitosis or meiosis & this is useful for carrying cell organelles
Part-d: chromosome: it is the hereditary material that carries genomic information for gene
expression & useful for inheritance of parental traits to offspring
Mitosis ---> somatic cell division & produces two identical daughter cells with equal number of
chromosomes (cytokinesis & karyokinesis).
Meiosis ----> a reduction division occurs in reproductive germ cells in which allosomes
determine sex determination finally generates half of the chromosomes in daughter cells
Part-a: Mitosis: it is a somatic cell division in an organism & this division is useful to maintain
body growth
Part-b: Meiosis: it is the reproductive reduction cell division & it is useful to produce gametes for
fertilization finally to generate a mature embryo
Part-c: cytokinesis: It is defined as the process of division of cytoplasm during cell division
either in mitosis or meiosis & this is useful for carrying cell organelles
Part-d: chromosome: it is the hereditary material that carries genomic information for gene
expression & useful for inheritance of parental traits to offspring
Cell plate is absent during animal cell division instead a complete cleavage of the cells during
division can be observed in animal cells. Cell plate formation during cell division observed only
in plants.
Haploid cells (n) are normally produced by reduction division of meiosis from diploid parent
cells (2n). This type of division occurs in germ cells of male and female species. The
chromosomes of the diploid germ cell undergo reduction in meiosis I and generate half of the
chromosomes when compared to parent diploid cell.
Meiosis division in a reproductive cell often results in four haploid cells with only single set of
chromosomes.
Meiosis-I prophase-I In this process double stranded homologous chromosomes line up each
other, and result in forming a tetrad; this is termed as Synapsis.
Terminal chaismata hold the homologous chromosomes together in metaphase I finally these are
going to align on the metaphase plate. Synapsis allows homologous chromosomes to travel to the
center by forming spindle formation through microtubules attaching to the centromeres finally to
the opposite poles of the cell. Later, crossing over takes place to exchanges paternal and maternal
genes to form tetrad where genetic variation occurs. Crossing over takes place to exchange equal
amounts of DNA generates genetic variability in prophase -I of meiosis.
Crossing over occurs in which lined up chromosomal ends exchange genetic information by
switching their places. Crossing over can un.
Proportional tax is a tax where the rate of tax is fixed. It is a pr.pdfsutharbharat59
Proportional tax is a tax where the rate of tax is fixed. It is a predetermined fixed percentage of
one’s income if it is an income tax or it is a fixed percentage of the value of the product if it is a
sales tax. It is also called flat tax. It is regressive in application as all the people pay same
amount. Hence the people earning less pay a higher percentage of their income and the people
paying more pay lesser percentage of their income.
Progressive tax is a tax where the rate of taxation increases with the increase in income or value
of products. Usually this is done by applying brackets to the income or value of products. For
example, people with income from 0 to 20000 fall in one bracket and hence the rate of taxation is
the same for the bracket as a whole let’s say 10%. People with income from 20001 to 40000 fall
in another bracket and they have a different rate of taxation let’s say 12%.Progressive tax works
on the logic of “ability to pay”.
Creating value without producing something new is done by exchanging one good or service
with other. This is done by estimating the exchange value of the goods or services to be
exchanged. The quantified worth of one good or service expressed in terms of the worth of
another is known as the exchange value. In the business of foreign exchange, the value of each
currency is expressed in terms of value of another currency to be exchanged. This creates and
exchange value or exchange rate of one currency to another.
A private currency is a currency issued by private organizations. In many countries it is illegal to
issue private paper currencies. Such a system (of private currencies) will create a protection
against inflation. Once an available instrument or arrangement for investment of present, add-
valuing currency could be created, the public would invest in great numbers, because they would
want to relieve themselves of the fear of devaluing money.
Interest would exist in a pure economy if there is a positive time preference. Time preference is
nothing but, the relative valuation placed on a good at an earlier date compared to its valuation at
a later date. Interest is thus explained as the propensity of individuals to discount the future. A
positive time preference is a necessary and sufficient condition for the existence of Interest in
any economy.
Static view is when resources are allocated efficiently at a point in time. An example of static
efficiency would be whether a firm could produce 2million cars a year more cheaply by using
more labor and less capital. Productive and allocative efficiency are static concepts of efficiency,
they can be used to discuss whether more could be produced now if resources were allocated in a
different way. These concepts can be used for instance, to discuss whether industries dominated
by a monopoly producer might produce at lower cost if competition were introduced in the
industry.
Dynamic view is concerned with how resoures are allocated over a period of tim.
POS system is a networked invironment where a main computer linked t.pdfsutharbharat59
POS system is a networked invironment where a main computer linked to multiple checkout
terminals.With a POS system:
The Design considerations of POS system:
Thanks
Solution
POS system is a networked invironment where a main computer linked to multiple checkout
terminals.With a POS system:
The Design considerations of POS system:
Thanks.
Model Attribute Check Company Auto PropertyCeline George
In Odoo, the multi-company feature allows you to manage multiple companies within a single Odoo database instance. Each company can have its own configurations while still sharing common resources such as products, customers, and suppliers.
Operation “Blue Star” is the only event in the history of Independent India where the state went into war with its own people. Even after about 40 years it is not clear if it was culmination of states anger over people of the region, a political game of power or start of dictatorial chapter in the democratic setup.
The people of Punjab felt alienated from main stream due to denial of their just demands during a long democratic struggle since independence. As it happen all over the word, it led to militant struggle with great loss of lives of military, police and civilian personnel. Killing of Indira Gandhi and massacre of innocent Sikhs in Delhi and other India cities was also associated with this movement.
How to Make a Field invisible in Odoo 17Celine George
It is possible to hide or invisible some fields in odoo. Commonly using “invisible” attribute in the field definition to invisible the fields. This slide will show how to make a field invisible in odoo 17.
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdfTechSoup
In this webinar you will learn how your organization can access TechSoup's wide variety of product discount and donation programs. From hardware to software, we'll give you a tour of the tools available to help your nonprofit with productivity, collaboration, financial management, donor tracking, security, and more.
2024.06.01 Introducing a competency framework for languag learning materials ...Sandy Millin
http://sandymillin.wordpress.com/iateflwebinar2024
Published classroom materials form the basis of syllabuses, drive teacher professional development, and have a potentially huge influence on learners, teachers and education systems. All teachers also create their own materials, whether a few sentences on a blackboard, a highly-structured fully-realised online course, or anything in between. Despite this, the knowledge and skills needed to create effective language learning materials are rarely part of teacher training, and are mostly learnt by trial and error.
Knowledge and skills frameworks, generally called competency frameworks, for ELT teachers, trainers and managers have existed for a few years now. However, until I created one for my MA dissertation, there wasn’t one drawing together what we need to know and do to be able to effectively produce language learning materials.
This webinar will introduce you to my framework, highlighting the key competencies I identified from my research. It will also show how anybody involved in language teaching (any language, not just English!), teacher training, managing schools or developing language learning materials can benefit from using the framework.
The Roman Empire A Historical Colossus.pdfkaushalkr1407
The Roman Empire, a vast and enduring power, stands as one of history's most remarkable civilizations, leaving an indelible imprint on the world. It emerged from the Roman Republic, transitioning into an imperial powerhouse under the leadership of Augustus Caesar in 27 BCE. This transformation marked the beginning of an era defined by unprecedented territorial expansion, architectural marvels, and profound cultural influence.
The empire's roots lie in the city of Rome, founded, according to legend, by Romulus in 753 BCE. Over centuries, Rome evolved from a small settlement to a formidable republic, characterized by a complex political system with elected officials and checks on power. However, internal strife, class conflicts, and military ambitions paved the way for the end of the Republic. Julius Caesar’s dictatorship and subsequent assassination in 44 BCE created a power vacuum, leading to a civil war. Octavian, later Augustus, emerged victorious, heralding the Roman Empire’s birth.
Under Augustus, the empire experienced the Pax Romana, a 200-year period of relative peace and stability. Augustus reformed the military, established efficient administrative systems, and initiated grand construction projects. The empire's borders expanded, encompassing territories from Britain to Egypt and from Spain to the Euphrates. Roman legions, renowned for their discipline and engineering prowess, secured and maintained these vast territories, building roads, fortifications, and cities that facilitated control and integration.
The Roman Empire’s society was hierarchical, with a rigid class system. At the top were the patricians, wealthy elites who held significant political power. Below them were the plebeians, free citizens with limited political influence, and the vast numbers of slaves who formed the backbone of the economy. The family unit was central, governed by the paterfamilias, the male head who held absolute authority.
Culturally, the Romans were eclectic, absorbing and adapting elements from the civilizations they encountered, particularly the Greeks. Roman art, literature, and philosophy reflected this synthesis, creating a rich cultural tapestry. Latin, the Roman language, became the lingua franca of the Western world, influencing numerous modern languages.
Roman architecture and engineering achievements were monumental. They perfected the arch, vault, and dome, constructing enduring structures like the Colosseum, Pantheon, and aqueducts. These engineering marvels not only showcased Roman ingenuity but also served practical purposes, from public entertainment to water supply.
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxEduSkills OECD
Andreas Schleicher presents at the OECD webinar ‘Digital devices in schools: detrimental distraction or secret to success?’ on 27 May 2024. The presentation was based on findings from PISA 2022 results and the webinar helped launch the PISA in Focus ‘Managing screen time: How to protect and equip students against distraction’ https://www.oecd-ilibrary.org/education/managing-screen-time_7c225af4-en and the OECD Education Policy Perspective ‘Students, digital devices and success’ can be found here - https://oe.cd/il/5yV
Synthetic Fiber Construction in lab .pptxPavel ( NSTU)
Synthetic fiber production is a fascinating and complex field that blends chemistry, engineering, and environmental science. By understanding these aspects, students can gain a comprehensive view of synthetic fiber production, its impact on society and the environment, and the potential for future innovations. Synthetic fibers play a crucial role in modern society, impacting various aspects of daily life, industry, and the environment. ynthetic fibers are integral to modern life, offering a range of benefits from cost-effectiveness and versatility to innovative applications and performance characteristics. While they pose environmental challenges, ongoing research and development aim to create more sustainable and eco-friendly alternatives. Understanding the importance of synthetic fibers helps in appreciating their role in the economy, industry, and daily life, while also emphasizing the need for sustainable practices and innovation.
The Art Pastor's Guide to Sabbath | Steve ThomasonSteve Thomason
What is the purpose of the Sabbath Law in the Torah. It is interesting to compare how the context of the law shifts from Exodus to Deuteronomy. Who gets to rest, and why?
We all have good and bad thoughts from time to time and situation to situation. We are bombarded daily with spiraling thoughts(both negative and positive) creating all-consuming feel , making us difficult to manage with associated suffering. Good thoughts are like our Mob Signal (Positive thought) amidst noise(negative thought) in the atmosphere. Negative thoughts like noise outweigh positive thoughts. These thoughts often create unwanted confusion, trouble, stress and frustration in our mind as well as chaos in our physical world. Negative thoughts are also known as “distorted thinking”.
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
Interfacepackage PJ1; public interface SimpleFractionInterface.pdf
1. Interface
package PJ1;
public interface SimpleFractionInterface
{
/** Task: Sets a fraction to a given value.
* @param num is the integer numerator
* @param den is the integer denominator
* @throw ArithmeticException if denominator is 0 */
public void setSimpleFraction(int num, int den);
/** Task: convert a fraction to double value
* @return the double floating point value of a fraction */
public double toDouble();
/** Task: Adds two fractions.
* @param secondFraction is a fraction that is the second operand of the addition
* @return a fraction which is the sum of the invoking fraction and the secondFraction */
public SimpleFractionInterface add(SimpleFractionInterface secondFraction);
/** Task: Subtracts two fractions.
* @param secondFraction a fraction that is the second operand of the subtraction
* @return a fraction which is the difference of the invoking fraction and the second operand */
public SimpleFractionInterface subtract(SimpleFractionInterface secondFraction);
/** Task: Multiplies two fractions.
* @param secondFraction a fraction that is the second operand of the multiplication
* @return a fraction which is the product of the invoking fraction and the secondFraction*/
public SimpleFractionInterface multiply(SimpleFractionInterface secondFraction);
/** Task: Divides two fractions.
* @param secondFraction a fraction that is the second operand of the division
* @return a fraction which the quotient of the invoking fraction and the secondFraction
* @throw FractionException if secondFraction is 0 */
public SimpleFractionInterface divide(SimpleFractionInterface secondFraction);
/** Task: Get's the fraction's reciprocal
* @return the reciprocal of the invoking fraction
* @throw FractionException if the new number with denominator is 0*/
public SimpleFractionInterface getReciprocal();
}
exception class
2. package PJ1;
public class SimpleFractionException extends RuntimeException
{
public SimpleFractionException()
{
this("");
}
public SimpleFractionException(String errorMsg)
{
super(errorMsg);
}
}
class with main method
package PJ1;
public class SimpleFraction implements SimpleFractionInterface, Comparable
{
// integer numerator and denominator
private int num;
private int den;
public SimpleFraction()
{
setSimpleFraction(0,1);// default numbers
} // end of the default constructor
public SimpleFraction(int num, int den)
{
setSimpleFraction(num, den);//
} // end constructor
public void setSimpleFraction(int num, int den)
{
if (den == 0)
throw new SimpleFractionException("denominator cannot be 0");
else{
this.num= num;
3. this.den= den;
}
reduceSimpleFractionToLowestTerms();
} // end setSimpleFraction
public double toDouble()
{
// return double floating point value
return (double) num/den;
} // end toDouble
public SimpleFractionInterface add(SimpleFractionInterface secondFraction)
{
SimpleFraction secondFraction2;
secondFraction2 = (SimpleFraction) secondFraction;
// a/b + c/d is (ad + cb)/(bd)
int newNum = num*secondFraction2.getDen() + secondFraction2.getNum()*den;
int newDen = den*secondFraction2.getDen();
// return result which is a new SimpleFraction object
return new SimpleFraction(newNum,newDen);
} // end add
public SimpleFractionInterface subtract(SimpleFractionInterface secondFraction)
{
SimpleFraction secondFraction2;
secondFraction2 = (SimpleFraction) secondFraction;
// a/b - c/d is (ad - cb)/(bd)
int newNum = num*secondFraction2.getDen()-secondFraction2.getNum()*den;
int newDen = den*secondFraction2.getDen();
// return result which is a new SimpleFraction object
return new SimpleFraction(newNum,newDen);
} // end subtract
public SimpleFractionInterface multiply(SimpleFractionInterface secondFraction)
{
SimpleFraction secondFraction2;
secondFraction2 = (SimpleFraction) secondFraction;
// a/b * c/d is (ac)/(bd)
4. int newNum = num*secondFraction2.getNum();
int newDen = den*secondFraction2.getDen();
// return result which is a new SimpleFraction object
return new SimpleFraction(newNum,newDen);
} // end multiply
public SimpleFractionInterface divide(SimpleFractionInterface secondFraction)
{
SimpleFraction secondFraction2;
secondFraction2 = (SimpleFraction) secondFraction;
// a/b / c/d is (ad)/(bc)
// return SimpleFractionException if secondFraction is 0
if (secondFraction2.getNum() == 0)
throw new SimpleFractionException("The second fraction cannot be 0");
int newNum= num*secondFraction2.getDen();
int newDen= den*secondFraction2.getNum();
// return result which is a new SimpleFraction object
return new SimpleFraction(newNum,newDen);
} // end divide
public SimpleFractionInterface getReciprocal()
{
SimpleFraction r;
// return SimpleFractionException if secondFraction is 0
if(den == 0)
throw new SimpleFractionException("The second fraction cannot be 0");
else
r = new SimpleFraction(den,num);
// return result which is a new SimpleFraction object
return r;
} // end getReciprocal
public boolean equals(Object other)
{
boolean result = false;
if(other instanceof SimpleFraction){
SimpleFraction otherSimple = (SimpleFraction) other;
if(compareTo(otherSimple) == 0)
5. result = true;
}
return result;
} // end equals
public int compareTo(SimpleFraction other)
{
if(toDouble() == other.toDouble())
return 0;
else if(toDouble() > other.toDouble())
return 1;
else
return -1;
} // end compareTo
public String toString()
{
return num + "/" + den;
} // end toString
/** Task: Reduces a fraction to lowest terms. */
// private methods start here
private int getNum(){
return num;
}
private int getDen(){
return den;
}
private void reduceSimpleFractionToLowestTerms()
{
// Outline:
// compute GCD of num & den
// GCD works for + numbers.
// So, you should eliminate - sign
// then reduce numbers : num/GCD and den/GCD
int sign = 1; //1= positive numbers; -1 = negative numbers
6. if(num < 0){ //number negative
sign = -1*sign;
num = num*-1;
}
if (den < 0){
sign= -1*sign;
den = den*-1;
}
int gcd= GCD(num,den);
num= (num/gcd)*sign;
den= den/gcd;
} // end reduceSimpleFractionToLowestTerms
/** Task: Computes the greatest common divisor of two integers.
* @param integerOne an integer
* @param integerTwo another integer
* @return the greatest common divisor of the two integers */
private int GCD(int integerOne, int integerTwo)
{
int result;
if (integerOne % integerTwo == 0)
result = integerTwo;
else
result = GCD(integerTwo, integerOne % integerTwo);
return result;
} // end GCD
//-----------------------------------------------------------------
// Simple test is provided here
public static void main(String[] args)
{
SimpleFractionInterface firstOperand = null;
SimpleFractionInterface secondOperand = null;
SimpleFractionInterface result = null;
double doubleResult = 0.0;
SimpleFraction nineSixteenths = new SimpleFraction(9, 16); // 9/16
SimpleFraction oneFourth = new SimpleFraction(1, 4); // 1/4
7. System.out.println(" ========================================= ");
// 7/8 + 9/16
firstOperand = new SimpleFraction(7, 8);
result = firstOperand.add(nineSixteenths);
System.out.println("The sum of " + firstOperand + " and " +
nineSixteenths + " is tt" + result);
System.out.println("tExpected result :tt23/16 ");
// 9/16 - 7/8
firstOperand = nineSixteenths;
secondOperand = new SimpleFraction(7, 8);
result = firstOperand.subtract(secondOperand);
System.out.println("The difference of " + firstOperand +
" and " + secondOperand + " is t" + result);
System.out.println("tExpected result :tt-5/16 ");
// 15/-2 * 1/4
firstOperand = new SimpleFraction(15, -2);
result = firstOperand.multiply(oneFourth);
System.out.println("The product of " + firstOperand +
" and " + oneFourth + " is t" + result);
System.out.println("tExpected result :tt-15/8 ");
// (-21/2) / (3/7)
firstOperand = new SimpleFraction(-21, 2);
secondOperand= new SimpleFraction(3, 7);
result = firstOperand.divide(secondOperand);
System.out.println("The quotient of " + firstOperand +
" and " + secondOperand + " is t" + result);
System.out.println("tExpected result :tt-49/2 ");
// -21/2 + 7/8
firstOperand = new SimpleFraction(-21, 2);
secondOperand= new SimpleFraction(7, 8);
result = firstOperand.add(secondOperand);
System.out.println("The sum of " + firstOperand +
" and " + secondOperand + " is tt" + result);
System.out.println("tExpected result :tt-77/8 ");
// 0/10, 5/(-15), (-22)/7
firstOperand = new SimpleFraction(0, 10);
8. doubleResult = firstOperand.toDouble();
System.out.println("The double floating point value of " + firstOperand + " is t" +
doubleResult);
System.out.println("tExpected result ttt0.0 ");
firstOperand = new SimpleFraction(1, -3);
doubleResult = firstOperand.toDouble();
System.out.println("The double floating point value of " + firstOperand + " is t" +
doubleResult);
System.out.println("tExpected result ttt-0.333333333... ");
firstOperand = new SimpleFraction(-22, 7);
doubleResult = firstOperand.toDouble();
System.out.println("The double floating point value of " + firstOperand + " is t" +
doubleResult);
System.out.println("tExpected result ttt-3.142857142857143");
System.out.println(" ========================================= ");
firstOperand = new SimpleFraction(-21, 2);
System.out.println("First = " + firstOperand);
// equality check
System.out.println("check First equals First: ");
if (firstOperand.equals(firstOperand))
System.out.println("Identity of fractions OK");
else
System.out.println("ERROR in identity of fractions");
secondOperand = new SimpleFraction(-42, 4);
System.out.println(" Second = " + secondOperand);
System.out.println("check First equals Second: ");
if (firstOperand.equals(secondOperand))
System.out.println("Equality of fractions OK");
else
System.out.println("ERROR in equality of fractions");
// comparison check
SimpleFraction first = (SimpleFraction)firstOperand;
SimpleFraction second = (SimpleFraction)secondOperand;
System.out.println(" check First compareTo Second: ");
if (first.compareTo(second) == 0)
9. System.out.println("SimpleFractions == operator OK");
else
System.out.println("ERROR in fractions == operator");
second = new SimpleFraction(7, 8);
System.out.println(" Second = " + second);
System.out.println("check First compareTo Second: ");
if (first.compareTo(second) < 0)
System.out.println("SimpleFractions < operator OK");
else
System.out.println("ERROR in fractions < operator");
System.out.println(" check Second compareTo First: ");
if (second.compareTo(first) > 0)
System.out.println("SimpleFractions > operator OK");
else
System.out.println("ERROR in fractions > operator");
System.out.println(" =========================================");
System.out.println(" check SimpleFractionException: 1/0");
try {
SimpleFraction a1 = new SimpleFraction(1, 0);
System.out.println("Error! No SimpleFractionException");
}
catch ( SimpleFractionException fe )
{
System.err.printf( "Exception: %s ", fe );
} // end catch
System.out.println("Expected result : SimpleFractionException! ");
System.out.println(" check SimpleFractionException: division");
try {
SimpleFraction a2 = new SimpleFraction();
SimpleFraction a3 = new SimpleFraction(1, 2);
a3.divide(a2);
System.out.println("Error! No SimpleFractionException");
}
catch ( SimpleFractionException fe )
{
System.err.printf( "Exception: %s ", fe );
10. } // end catch
System.out.println("Expected result : SimpleFractionException! ");
} // end main
} // end SimpleFraction
output:
run:
=========================================
The sum of 7/8 and 9/16 is 23/16
Expected result : 23/16
The difference of 9/16 and 7/8 is -5/16
Expected result : -5/16
The product of -15/2 and 1/4 is -15/8
Expected result : -15/8
The quotient of -21/2 and 3/7 is -49/2
Expected result : -49/2
The sum of -21/2 and 7/8 is -77/8
Expected result : -77/8
The double floating point value of 0/1 is 0.0
Expected result 0.0
The double floating point value of -1/3 is -0.3333333333333333
Expected result -0.333333333...
The double floating point value of -22/7 is -3.142857142857143
Expected result -3.142857142857143
=========================================
First = -21/2
check First equals First:
Identity of fractions OK
Second = -21/2
check First equals Second:
Equality of fractions OK
check First compareTo Second:
SimpleFractions == operator OK
Second = 7/8
check First compareTo Second:
SimpleFractions < operator OK
11. check Second compareTo First:
SimpleFractions > operator OK
=========================================
check SimpleFractionException: 1/0
Exception: PJ1.SimpleFractionException: denominator cannot be 0
Expected result : SimpleFractionException!
check SimpleFractionException: division
Exception: PJ1.SimpleFractionException: The second fraction cannot be 0
Expected result : SimpleFractionException!
BUILD SUCCESSFUL (total time: 3 seconds)
Solution
Interface
package PJ1;
public interface SimpleFractionInterface
{
/** Task: Sets a fraction to a given value.
* @param num is the integer numerator
* @param den is the integer denominator
* @throw ArithmeticException if denominator is 0 */
public void setSimpleFraction(int num, int den);
/** Task: convert a fraction to double value
* @return the double floating point value of a fraction */
public double toDouble();
/** Task: Adds two fractions.
* @param secondFraction is a fraction that is the second operand of the addition
* @return a fraction which is the sum of the invoking fraction and the secondFraction */
public SimpleFractionInterface add(SimpleFractionInterface secondFraction);
/** Task: Subtracts two fractions.
* @param secondFraction a fraction that is the second operand of the subtraction
* @return a fraction which is the difference of the invoking fraction and the second operand */
public SimpleFractionInterface subtract(SimpleFractionInterface secondFraction);
/** Task: Multiplies two fractions.
* @param secondFraction a fraction that is the second operand of the multiplication
12. * @return a fraction which is the product of the invoking fraction and the secondFraction*/
public SimpleFractionInterface multiply(SimpleFractionInterface secondFraction);
/** Task: Divides two fractions.
* @param secondFraction a fraction that is the second operand of the division
* @return a fraction which the quotient of the invoking fraction and the secondFraction
* @throw FractionException if secondFraction is 0 */
public SimpleFractionInterface divide(SimpleFractionInterface secondFraction);
/** Task: Get's the fraction's reciprocal
* @return the reciprocal of the invoking fraction
* @throw FractionException if the new number with denominator is 0*/
public SimpleFractionInterface getReciprocal();
}
exception class
package PJ1;
public class SimpleFractionException extends RuntimeException
{
public SimpleFractionException()
{
this("");
}
public SimpleFractionException(String errorMsg)
{
super(errorMsg);
}
}
class with main method
package PJ1;
public class SimpleFraction implements SimpleFractionInterface, Comparable
{
// integer numerator and denominator
private int num;
private int den;
public SimpleFraction()
{
13. setSimpleFraction(0,1);// default numbers
} // end of the default constructor
public SimpleFraction(int num, int den)
{
setSimpleFraction(num, den);//
} // end constructor
public void setSimpleFraction(int num, int den)
{
if (den == 0)
throw new SimpleFractionException("denominator cannot be 0");
else{
this.num= num;
this.den= den;
}
reduceSimpleFractionToLowestTerms();
} // end setSimpleFraction
public double toDouble()
{
// return double floating point value
return (double) num/den;
} // end toDouble
public SimpleFractionInterface add(SimpleFractionInterface secondFraction)
{
SimpleFraction secondFraction2;
secondFraction2 = (SimpleFraction) secondFraction;
// a/b + c/d is (ad + cb)/(bd)
int newNum = num*secondFraction2.getDen() + secondFraction2.getNum()*den;
int newDen = den*secondFraction2.getDen();
// return result which is a new SimpleFraction object
return new SimpleFraction(newNum,newDen);
} // end add
public SimpleFractionInterface subtract(SimpleFractionInterface secondFraction)
{
14. SimpleFraction secondFraction2;
secondFraction2 = (SimpleFraction) secondFraction;
// a/b - c/d is (ad - cb)/(bd)
int newNum = num*secondFraction2.getDen()-secondFraction2.getNum()*den;
int newDen = den*secondFraction2.getDen();
// return result which is a new SimpleFraction object
return new SimpleFraction(newNum,newDen);
} // end subtract
public SimpleFractionInterface multiply(SimpleFractionInterface secondFraction)
{
SimpleFraction secondFraction2;
secondFraction2 = (SimpleFraction) secondFraction;
// a/b * c/d is (ac)/(bd)
int newNum = num*secondFraction2.getNum();
int newDen = den*secondFraction2.getDen();
// return result which is a new SimpleFraction object
return new SimpleFraction(newNum,newDen);
} // end multiply
public SimpleFractionInterface divide(SimpleFractionInterface secondFraction)
{
SimpleFraction secondFraction2;
secondFraction2 = (SimpleFraction) secondFraction;
// a/b / c/d is (ad)/(bc)
// return SimpleFractionException if secondFraction is 0
if (secondFraction2.getNum() == 0)
throw new SimpleFractionException("The second fraction cannot be 0");
int newNum= num*secondFraction2.getDen();
int newDen= den*secondFraction2.getNum();
// return result which is a new SimpleFraction object
return new SimpleFraction(newNum,newDen);
} // end divide
public SimpleFractionInterface getReciprocal()
{
SimpleFraction r;
// return SimpleFractionException if secondFraction is 0
if(den == 0)
15. throw new SimpleFractionException("The second fraction cannot be 0");
else
r = new SimpleFraction(den,num);
// return result which is a new SimpleFraction object
return r;
} // end getReciprocal
public boolean equals(Object other)
{
boolean result = false;
if(other instanceof SimpleFraction){
SimpleFraction otherSimple = (SimpleFraction) other;
if(compareTo(otherSimple) == 0)
result = true;
}
return result;
} // end equals
public int compareTo(SimpleFraction other)
{
if(toDouble() == other.toDouble())
return 0;
else if(toDouble() > other.toDouble())
return 1;
else
return -1;
} // end compareTo
public String toString()
{
return num + "/" + den;
} // end toString
/** Task: Reduces a fraction to lowest terms. */
// private methods start here
private int getNum(){
return num;
}
16. private int getDen(){
return den;
}
private void reduceSimpleFractionToLowestTerms()
{
// Outline:
// compute GCD of num & den
// GCD works for + numbers.
// So, you should eliminate - sign
// then reduce numbers : num/GCD and den/GCD
int sign = 1; //1= positive numbers; -1 = negative numbers
if(num < 0){ //number negative
sign = -1*sign;
num = num*-1;
}
if (den < 0){
sign= -1*sign;
den = den*-1;
}
int gcd= GCD(num,den);
num= (num/gcd)*sign;
den= den/gcd;
} // end reduceSimpleFractionToLowestTerms
/** Task: Computes the greatest common divisor of two integers.
* @param integerOne an integer
* @param integerTwo another integer
* @return the greatest common divisor of the two integers */
private int GCD(int integerOne, int integerTwo)
{
int result;
if (integerOne % integerTwo == 0)
result = integerTwo;
else
17. result = GCD(integerTwo, integerOne % integerTwo);
return result;
} // end GCD
//-----------------------------------------------------------------
// Simple test is provided here
public static void main(String[] args)
{
SimpleFractionInterface firstOperand = null;
SimpleFractionInterface secondOperand = null;
SimpleFractionInterface result = null;
double doubleResult = 0.0;
SimpleFraction nineSixteenths = new SimpleFraction(9, 16); // 9/16
SimpleFraction oneFourth = new SimpleFraction(1, 4); // 1/4
System.out.println(" ========================================= ");
// 7/8 + 9/16
firstOperand = new SimpleFraction(7, 8);
result = firstOperand.add(nineSixteenths);
System.out.println("The sum of " + firstOperand + " and " +
nineSixteenths + " is tt" + result);
System.out.println("tExpected result :tt23/16 ");
// 9/16 - 7/8
firstOperand = nineSixteenths;
secondOperand = new SimpleFraction(7, 8);
result = firstOperand.subtract(secondOperand);
System.out.println("The difference of " + firstOperand +
" and " + secondOperand + " is t" + result);
System.out.println("tExpected result :tt-5/16 ");
// 15/-2 * 1/4
firstOperand = new SimpleFraction(15, -2);
result = firstOperand.multiply(oneFourth);
System.out.println("The product of " + firstOperand +
" and " + oneFourth + " is t" + result);
System.out.println("tExpected result :tt-15/8 ");
// (-21/2) / (3/7)
firstOperand = new SimpleFraction(-21, 2);
secondOperand= new SimpleFraction(3, 7);
18. result = firstOperand.divide(secondOperand);
System.out.println("The quotient of " + firstOperand +
" and " + secondOperand + " is t" + result);
System.out.println("tExpected result :tt-49/2 ");
// -21/2 + 7/8
firstOperand = new SimpleFraction(-21, 2);
secondOperand= new SimpleFraction(7, 8);
result = firstOperand.add(secondOperand);
System.out.println("The sum of " + firstOperand +
" and " + secondOperand + " is tt" + result);
System.out.println("tExpected result :tt-77/8 ");
// 0/10, 5/(-15), (-22)/7
firstOperand = new SimpleFraction(0, 10);
doubleResult = firstOperand.toDouble();
System.out.println("The double floating point value of " + firstOperand + " is t" +
doubleResult);
System.out.println("tExpected result ttt0.0 ");
firstOperand = new SimpleFraction(1, -3);
doubleResult = firstOperand.toDouble();
System.out.println("The double floating point value of " + firstOperand + " is t" +
doubleResult);
System.out.println("tExpected result ttt-0.333333333... ");
firstOperand = new SimpleFraction(-22, 7);
doubleResult = firstOperand.toDouble();
System.out.println("The double floating point value of " + firstOperand + " is t" +
doubleResult);
System.out.println("tExpected result ttt-3.142857142857143");
System.out.println(" ========================================= ");
firstOperand = new SimpleFraction(-21, 2);
System.out.println("First = " + firstOperand);
// equality check
System.out.println("check First equals First: ");
if (firstOperand.equals(firstOperand))
System.out.println("Identity of fractions OK");
else
System.out.println("ERROR in identity of fractions");
19. secondOperand = new SimpleFraction(-42, 4);
System.out.println(" Second = " + secondOperand);
System.out.println("check First equals Second: ");
if (firstOperand.equals(secondOperand))
System.out.println("Equality of fractions OK");
else
System.out.println("ERROR in equality of fractions");
// comparison check
SimpleFraction first = (SimpleFraction)firstOperand;
SimpleFraction second = (SimpleFraction)secondOperand;
System.out.println(" check First compareTo Second: ");
if (first.compareTo(second) == 0)
System.out.println("SimpleFractions == operator OK");
else
System.out.println("ERROR in fractions == operator");
second = new SimpleFraction(7, 8);
System.out.println(" Second = " + second);
System.out.println("check First compareTo Second: ");
if (first.compareTo(second) < 0)
System.out.println("SimpleFractions < operator OK");
else
System.out.println("ERROR in fractions < operator");
System.out.println(" check Second compareTo First: ");
if (second.compareTo(first) > 0)
System.out.println("SimpleFractions > operator OK");
else
System.out.println("ERROR in fractions > operator");
System.out.println(" =========================================");
System.out.println(" check SimpleFractionException: 1/0");
try {
SimpleFraction a1 = new SimpleFraction(1, 0);
System.out.println("Error! No SimpleFractionException");
}
catch ( SimpleFractionException fe )
{
20. System.err.printf( "Exception: %s ", fe );
} // end catch
System.out.println("Expected result : SimpleFractionException! ");
System.out.println(" check SimpleFractionException: division");
try {
SimpleFraction a2 = new SimpleFraction();
SimpleFraction a3 = new SimpleFraction(1, 2);
a3.divide(a2);
System.out.println("Error! No SimpleFractionException");
}
catch ( SimpleFractionException fe )
{
System.err.printf( "Exception: %s ", fe );
} // end catch
System.out.println("Expected result : SimpleFractionException! ");
} // end main
} // end SimpleFraction
output:
run:
=========================================
The sum of 7/8 and 9/16 is 23/16
Expected result : 23/16
The difference of 9/16 and 7/8 is -5/16
Expected result : -5/16
The product of -15/2 and 1/4 is -15/8
Expected result : -15/8
The quotient of -21/2 and 3/7 is -49/2
Expected result : -49/2
The sum of -21/2 and 7/8 is -77/8
Expected result : -77/8
The double floating point value of 0/1 is 0.0
Expected result 0.0
The double floating point value of -1/3 is -0.3333333333333333
Expected result -0.333333333...
The double floating point value of -22/7 is -3.142857142857143
21. Expected result -3.142857142857143
=========================================
First = -21/2
check First equals First:
Identity of fractions OK
Second = -21/2
check First equals Second:
Equality of fractions OK
check First compareTo Second:
SimpleFractions == operator OK
Second = 7/8
check First compareTo Second:
SimpleFractions < operator OK
check Second compareTo First:
SimpleFractions > operator OK
=========================================
check SimpleFractionException: 1/0
Exception: PJ1.SimpleFractionException: denominator cannot be 0
Expected result : SimpleFractionException!
check SimpleFractionException: division
Exception: PJ1.SimpleFractionException: The second fraction cannot be 0
Expected result : SimpleFractionException!
BUILD SUCCESSFUL (total time: 3 seconds)