r/badcode • • Nov 13 '20

java Getting Digits using Switch Catch

Post image
881 Upvotes

52 comments sorted by

View all comments

49

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Nov 13 '20

Image Transcription: Code


//gets the digit value and returns it as an int and if not valid, exists
public static int evalDigit(String in){
    int result = -1;
    switch (in){
        case "0":
            result = 0;
            break;
        case "1":
            result = 1;
            break;
        case "2":
            result = 2;
            break;
        case "3":
            result = 3;
            break;
        case "4":
            result = 4;
            break;
        case "5":
            result = 5;
            break;
        case "6":
            result = 6;
            break;
        case "7":
            result = 7;
            break;
        case "8":
            result = 8;
            break;
        case "9":
            result = 9;
            break;
        default:
            System.out.println("Invalid digit was entered, try again");
            System.exit(2);
    }
    return result;
}

I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!

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

8

u/HolySpecs Nov 13 '20

I would do that but I can't, I was tasked to only take in single digits, which is fun πŸ™ƒ

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

6

u/emacsos Nov 13 '20

You're going to need to try and get the first character though. This is a string, not a char

2

u/HolySpecs Nov 13 '20

Good point, I think I typed String out of habit but then it is part of a recursive function and I didn't wanna break it so yh πŸ™ƒ

2

u/whc2001 Nov 14 '20

Personally I like to write 0x30 and 0x39 since '0' is 0x30, '1' is 0x31...

3

u/SquirrelBlind Nov 13 '20

it's String, not char.

3

u/Tyfyter2002 Nov 13 '20

Which is part of the reason this is bad code, instead of using char it uses String and closes the program with an error message if the string given isn't a single character

2

u/mattmc318 Nov 14 '20

Good human