This site requires JavaScript, please enable it in your browser!
Greenfoot back
Theangryman
Theangryman wrote ...

2017/1/15

Divide by Zero Errors

Theangryman Theangryman

2017/1/15

#
Hey guys, I've literally just signed up to the greenfoot forums in the hopes of getting an error checked out by someone who knows what it is they're doing. I'm trying to implement a visual way of representing a percentage of a bar, somewhat akin to a health bar (and in the code shown, exactly like a health bar), in such a way where I'd be able to just change the parameters used in the World constructor to adjust how much of the bar is shown or not. However, despite the syntax being correct and the logic resulting in no actual divisions by zero as far as I'm aware, greenfoot keeps throwing errors at me. Here's my code: What's weird about it is that it worked before I tried to used the updateBar() method to also draw a label next to the health bar that said "Health", but couldn't get it to work so I reverted the changes. If I change the "private int curVar;" to "private int curVar = 5;", the world compiles but no red bar is drawn.
Super_Hippo Super_Hippo

2017/1/15

#
Try to move the calculation of 'pxPerHealthPoint' in front of the call to 'updateBar' in the constructor. When the code is executed, the variables are 0, so it tries to do 0/0. Oh and after decreasing 'curVar' in the 'loseValue' method, too.
danpost danpost

2017/1/16

#
It would be better to keep the maximum value of the bar in a field instead of the number of pixels per health point. The reason for this is simply because of inaccuracies in the rounded int value of the latter. To show what I mean, let us say, for example, that the width of the bar is 100 and the maximum value was 30. The calculated number of pixels per unit would end up to be 3. Now, when the current value of the bar is 30, the bar will only show 90% full (3 pixels per health point * 30 health points = 90 pixels). The colored portion of the bar should be calculated each time the value changes using the expression (barWidth * curVal / maxValue) presuming a minimum value of zero.
Theangryman Theangryman

2017/1/16

#
@Super_Hippo I tried out your method and it worked, thanks. @danpost Yeah, I understand what it is you're getting at, I had troubles using 120 as the max value when the length of the bar was 320 due to rounding errors, so instead I'm just gonna fudge it (read: be lazy) and make sure all the values I use are factors of 300 for the bar length and bar segment length.
You need to login to post a reply.