Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;    
} 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading