Rob Prime wrote:... With these ranges there are other tricks using % 10, % 100 and % 1000 as well:
Ah, but 100 % 10 is 0. (As with 1000, 10000, etc.)
There's something amusing in the fact that a guy named Prime overlooked this. Maybe he's not used to numbers having other factors.
On a related note though, it's worthwhile to pay attention to the ordering of if / else if / else clauses, and avoid needless redundancy. For this example here, I'd rather code it like this:
I replaced "Hola" with three different strings A-B-C, since otherwise the whole construct is pointless. Anyway, organizing the statements this way, we don't need to specify (for example) <=99 for one group, and >=100 for the next. We eliminate needless redundancy, and also make it easier to make alterations if we need to change the cutoff from 100 to, say, 256, in a future release. This way we only need to change one number, instead of two. And we're less likely to have problems because we said < instead of <, or because we refactored num to be a double rather than an int.
Rob Prime wrote:... With these ranges there are other tricks using % 10, % 100 and % 1000 as well:
Ah, but 100 % 10 is 0. (As with 1000, 10000, etc.)
You are so right of course. I was so busy about trying to prevent nested ifs that this slipped by. "&& num / 10 == 0" and "&& num / 100 == 0" should fix this. Or just stick with the simple range checking.
Mike Simmons wrote:There's something amusing in the fact that a guy named Prime overlooked this.
adam smith ii
Greenhorn
Joined: Feb 04, 2010
Posts: 20
posted
0
Rob Prime wrote:In this case, an if-else if-else if would seem better:
With these ranges there are other tricks using % 10, % 100 and % 1000 as well:
As well as other remarks about 0 remainder, will this code accomplish anything for any number not ending in 0? That is to say, the comparison of (num % (power of 10)) to zero will always be false using the remainder operator.
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32712
4
posted
0
I think that mistake has already been noticed
It might work better with / than %
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.