Search code examples
javaandroiddivide-by-zero

Why I am getting this error "Caused by: java.lang.ArithmeticException: divide by zero"?


How can i stop a values lower than <= 0. and its throw exception.

Logcat : Logcat error

RoundKnobButton.java file :

int size = GetJsonData.frequency.size();
        int a = Math.round((float)(360/size));
            int b = 0;
            try {
                Log.i("RoundKnob",".....Try");
                b = Math.round((float)(scaleDegrees/a));
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.i("RoundKnob", ".....catch");
            }

DialScreen.java file :

rv = new RoundKnobButton(this, R.drawable.circle, R.drawable.circle1,
            R.drawable.circle1, m_Inst.Scale(350), m_Inst.Scale(350));

So, If anyone know the problem solution or give me the idea to solve this error then tell me.


Solution

  • Let's have a look at this line:

    int a = Math.round((float)(360/size));
    

    And assume that size==361.

    Since size is an int we have an integer-division and 360/size equals 0. Then you cast it to a float resulting in 0.0f, round it (givin 0.0f) and assign it to an int that's also 0 as a result.

    What you probably meant to do is

    int a = Math.round(((float)360/size));
    

    Note the different parentheses...