r/badcode • • Nov 13 '20

java Getting Digits using Switch Catch

Post image
881 Upvotes

52 comments sorted by

View all comments

Show parent comments

23

u/OptimalMain Nov 13 '20

If(in >= 48 && in <= 57){ result = in - 48 }

39

u/ILikeSahne Nov 13 '20

Well but you are fucked when you don't know ascii, this is better: if(in >= '0' && in <= '9') { result = in - '0'; }

5

u/jim3692 Nov 13 '20

Does this work on Java? I know that it works on C and C++, but "in" must be char type.

4

u/qh4os Nov 14 '20

Actually the code they put doesn’t work at all — or rather it does, but not as they intended.

In this case they were actually comparing an address to a number (assuming String => char* in the case of C), which is perfectly valid, but that condition is likely never going to evaluate as true.

But even in Java, character literals are just numbers, so the comparison should be fine if that error is corrected