Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Fraction implementation using oops in java
/*package whatever //do not write package name here */ import java.io.*; import java.util.*; import java.lang.*; class Fraction{ private int numerator; private int denominator; public Fraction(int numerator,int denominator) { this.numerator=numerator; this.denominator=denominator; simplify(); } public int getDenominator() { return denominator; } public int getNumerator() { return numerator; } public void setNumerator(int n) { this.numerator=n; simplify(); } public void setDenominator(int d) { this.denominator=d; this.simplify(); } public void print() { if(denominator==1) { System.out.println(numerator); } else System.out.println(numerator+" / "+denominator); } private void simplify() { int gcd=1; for(int i=2;i<=Math.min(numerator,denominator);i++) { if(numerator%i==0 && denominator%i==0) { gcd=i; } } numerator=numerator/gcd; denominator=denominator/gcd; } public static Fraction add(Fraction f1,Fraction f2) { int x=f1.numerator*f2.denominator+f2.numerator*f1.denominator; int y=f1.denominator*f2.denominator; Fraction f3=new Fraction(x,y); return f3; } public void add(Fraction f) { this.numerator=this.numerator*f.denominator+this.denominator*f.numerator; this.denominator=this.denominator*f.denominator; simplify(); } public void multiply(Fraction f) { this.numerator=this.numerator*f.numerator; this.denominator=this.denominator*f.denominator; simplify(); } } class Rextester { public static void main (String[] args) { Fraction f1=new Fraction(20,30); f1.print(); f1.setNumerator(12); f1.print(); f1.setNumerator(10); f1.setDenominator(30); f1.print(); Fraction f2=new Fraction(30,40); f2.print(); f1.add(f2); f1.print(); Fraction f3=new Fraction(4,5); f3.multiply(f2); f3.print(); Fraction f4=Fraction.add(f3,f2);//3/5 3/4 f4.print(); } }
run
|
edit
|
history
|
help
0
MinMaxArray
클래스의 정의와 인스턴스 생성
program to count number of lines
Compiler
isPrime
jb12.0 threads.enums
Reverse a Linked List in groups of given size k
Quadratic equation
Apple Banana Pear question
AllStar