Mike
Mike

Reputation: 5

ArithmeticException division by zero... how to fix this method?

The purpose of this method is to iterate through a 2D array of integers called grid[][], and translate the integers based on the maximum and minimum values into a smaller range between 100 and 250 (the original minimum value becomes 100, the original maximum value becomes 250, and everything in between is calculated respectively). When this method is called, division by zero ArithmeticException occurs.

Clearly I'm making some logic mistakes here... I just don't see the fix. Can anyone help?

public int greenValues(int arrayVal) {  

    int max = 0;
    int min = 0;
    int colorValue = 0;
    int temp;

    for (int i = 0; i < grid.length; i++) {  // finds maximum and minimum numbers in file 
        for (int j = 0; j < grid.length; j++) {  
            if (max < grid[i][j]) {
                max = grid[i][j];   
            }
            if (min > grid[i][j]) { 
                min = grid[i][j];
            }
        }
    }

        int arrayRange = (max-min); // arrayVal, arrayRange, and max and min are 0
        temp = (((arrayVal-min) * COLOR_RANGE) / arrayRange) + 100;    // map values to range of 100 - 250
        colorValue = temp;
        return colorValue;
    }

Upvotes: 0

Views: 558

Answers (2)

Durlabh Sharma
Durlabh Sharma

Reputation: 48

Solution by Dilip is perfect. Or you can also add a conditional statement which lets it pass only when arrayRange is not 0 & execute something else if it is 0. But it'll increase overhead by executing the conditional statement every time arrayRange is calculated.

Upvotes: 1

Dilip Kumar
Dilip Kumar

Reputation: 2534

This line is culprint for producing ArithmaticExcpetion.

temp = (((arrayVal-min) * COLOR_RANGE) / arrayRange) + 100;

your calculating arrayRange dynamically as you don't know when that value will be 0. so you can wrap this line with try catch block to do some exception handling.

Upvotes: 2

Related Questions