user2197569
user2197569

Reputation: 5

I am getting java.lang.ArithmeticException error

This is inside the main method. Trying to compute the double x math formula and it is giving me problem running the code. Can someone please help?

final int P = Integer.parseInt(args[0]);
final int Q = Integer.parseInt(args[1]);
final double H = Double.parseDouble(args[2]);
final int N = Spiro.numberOfRevolutions(P, Q);

IPoint2D point = new IPoint2D(0., 0.);
SimpleDrawing.drawPoint(point);

for (int i = 1; i <= 360*N; i++) {
    final int r = P/Q;
    double radianI = Math.toRadians(i);
    double x = ((1 - r) * Math.cos(radianI)) + (H * Math.cos(((1- r) / r) *  radianI));
    double y = ((1 - r) * Math.sin(radianI)) + (H * Math.sin(((1- r) / r) * radianI));

    IPoint2D point1 = new IPoint2D(x,y);
    SimpleDrawing.drawPoint(point1);
}

Upvotes: 0

Views: 161

Answers (2)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280000

If P is smaller than Q (or Q is 0 will immediately throw the ArithmeticException)

final int r = P/Q;

r will have a value of 0. You then divide by r=0

double x = ((1 - r) * Math.cos(radianI)) + (H * Math.cos(((1- r) / r) *  radianI));

throwing the ArithmeticException.

Upvotes: 4

Crickcoder
Crickcoder

Reputation: 2155

When you are doing this :

final int r = P/Q;

You need to make sure Q is never zero, otherwise it would be ArithmeticException

Upvotes: 0

Related Questions