I am struggling with creation of a to calculate fractions and return in an array[3]. So if nominator is 7 and denominator is 3 it should return {2,1,3}, a fraction part and a integer part. If denominator is 0, the integer division should not be executed and I have to return null (not print it). That is what I am struggling with. My code is below:
public class Main{
public static int[] fraction(int nominator, int denominator){
int quota=0;
int numerator=0;
try{
quota = nominator / denominator;
numerator = nominator % denominator;
}
catch(java.lang.ArithmeticException e)
{
if(denominator==0)
{
quota =0;
numerator=0;
}
}
int [] integerArray ={quota, numerator,denominator};
return integerArray;
}
}
CodePudding user response:
As mentioned in the comments, you can just return early once you checked the denominator is 0.
public static int[] fraction(int nominator, int denominator){
if (denominator == 0){
return null
}
int quota = nominator / denominator;
int numerator = nominator % denominator;
int [] integerArray = {quota, numerator,denominator};
return integerArray;
}
CodePudding user response:
you can proceed in 2 different ways:
- you can control if denominator is 0 before the try and return null instantly (as said in the comments)
- you used try catch so you can return null into the catch block without further controls because you catch an exception
there should not be any compilation errors so if you get one try to read the console and find what's the problem.