0

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.

3
  • You need to verify that numTilesAcross is never zero. Since that is the only place you are dividing by a variable that you shared, and you didn't show us how numTilesAcross is defined there isn't much more help we can offer. Commented Feb 7, 2018 at 22:07
  • What is the value of numTilesAcross ? Commented Feb 7, 2018 at 22:07
  • @LyjuIEdwinson 0 too. Commented Feb 7, 2018 at 23:44

3 Answers 3

1

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

It seems that it works great !! Thank you so much for your help :)
0

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

1 Comment

Thank you very much, I will keep this part of the code in my mind in case I need it for specific purposes :P
0

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
}

1 Comment

I tried your code, it seems that this works great, I'll keep the code for when I need it, thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.