r/badcode • • Nov 13 '20

java Getting Digits using Switch Catch

Post image
881 Upvotes

52 comments sorted by

View all comments

16

u/HolySpecs Nov 13 '20 edited Nov 13 '20

So I was tasked to make a recursive parsing calculator and it could only take in single digits from 0 to 9, which resulted in me doing this mess. It was either this or using if statements so I chose the former.

Edit 1:

This was a task given to me from a teacher and they gave me specific requirements such as:

  • I can't use loops (no while, do repeat or for loops)

  • the format for the inputs are:

<EXP> = + <DIGIT> <EXP> | - <DIGIT> <EXP> | &<EXP> | <DIGIT>
<DIGIT> = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 

where + is for add, - is for subtract, and & is for sum from one to that number

This means if I want to, say do 3+4+5 I'd have to enter

+3+45

Thanks for the responses guys, it's really interesting to see other's perspectives!

Edit 2: Just realised I should've said Switch-case in the title, not switch-catch. I was thinking of try-catch.

Edit 3: the result = - 1 is just a placeholder, it's not really important

17

u/[deleted] Nov 13 '20

Just cast the string to an integer

6

u/HolySpecs Nov 13 '20 edited Nov 13 '20

Well yes, but the inputs were a mix of characters as well like:

+99
9
-98
&4
&4+89 (this line is wrong)

20

u/[deleted] Nov 13 '20

Well, in this case, the current code is not gonna work either.

I was gonna suggest you do:

try {

Integer.paseInt(in);

} catch(NumberFormatException exception) {

//Handle exception here

}

But if you need to process a non-numeric string, that'll require some other stuff.