in java i have this code i would like all the printing to happen in the constructor how would i do that import java.util.*;
in java i have this code i would like all the printing to happen in the constructor how would i do that
import java.util.*;
public class Rational{
int n;
int d;
Rational(int num,int den){
if(den==0){
throw new ArithmeticException("Can't divide by 0");
}
if(num==0 && den!=0)
{
num =0;
den=1;
}
if(den<0 && num>0)
{
den = den*(-1);
num = num *(-1);
}
if(den<0 && num<0)
{
den = den*(-1);
num = num *(-1);
}
int gcd =1;
for(int i = 1; i <= num && i <= den; i++)
{
if(num%i==0 && den%i==0)
gcd = i;
}
num = num / gcd;
den = den/gcd;
this.n=num;
this.d=den;
}
void print(){
System.out.print(this.n+"/"+this.d);
}
public static void main(String []args){
Scanner sc= new Scanner(System.in);
int a= sc.nextInt();
int b= sc.nextInt();
System.out.println("Constructor called with n = "+a+" and d = "+b);
Rational r1 = new Rational(a,b);
System.out.print("Result is : ");
r1.print();
}
}
Step by step
Solved in 4 steps with 2 images