Francesco Mesiano
Francesco Mesiano

Reputation: 25

Java Arithmetic Exception, how to resolve it?

a few moments ago I started my code in java until I got a problem ... In the console was present / written this:

Exception in thread "Thread-2" java.lang.ArithmeticException: / by zero.

at MyPackage.MyClass.draw (MyClass.java:180) ...

I went to the class where the error came from, this is the code:

if (map [row] [col] == 0) continue;

int rc = map [row] [col];

int r = rc / numTilesAcross;

int c = rc% numTilesAcross;

...

col and row have the value of 0 ... I do not understand where the problem is ... someone would help me?

Thanks so much.

Upvotes: 0

Views: 982

Answers (3)

user9330045
user9330045

Reputation: 36

The only place where division by zero in your program might occur is:

int r = rc / numTilesAcross;

that means, that you are trying to divide rc by 0 - numTilesAcross variable is holding a zero. If you want this to work, you need to make sure that numTilesAcross will never be zero when this is executed, e.g., use an if conditional:

if numTilesAcross == 0 {
    // do something else
} else {
    int r = rc / numTilesAcross;
}

Upvotes: 1

Bucket
Bucket

Reputation: 7521

Well, you're obviously dividing by zero. The only place this could occur in the code you provided is in numTilesAcross. Add a check to prevent this code from running if this evaluates to 0.

if (map [row] [col] == 0) continue;

int rc = map [row] [col];
int r, c;

if(numTilesAcross != 0) {
    r = rc / numTilesAcross;
    c = rc % numTilesAcross;
} else {
    //do something when numTilesAcross = 0
}

Upvotes: 0

bejohi
bejohi

Reputation: 13

The Exception is very clear: You divided by zero. Since you have only one division in your code

int r = rc / numTilesAcross;

the Exception will be thrown in this line, if numTilesAcross is exactly 0.

I suggest you find out why it is zero and don't process this case, e.g. by just adding a check before:

if(numTilesAcross != 0){
    int r = rc / numTilesAcross;
}

Upvotes: 0

Related Questions