Skip to content
Advertisement

How can I return null of denominator is 0 in this method Java

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; 
    
  } 

}

Advertisement

Answer

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;    
} 
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement