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

6

u/TheYaINN Nov 13 '20

None of those are the correct solution, it would take me some time but you should look into a parser. Given a language you can write a parser, that would throw an error on the the input you gave on another comment. The parse is build into several function, where input of a lower operator is the input of a higher operator, eg. Input for + or - operation is the result of * or / operation, which finally cascades down to a single method that reads the integer values. If the character is not parseable the parser would throw an error, where you could improve error handling, to a degree that tells the user what is wrong and at what position, since that is a known property of your currently parsing string.

Sorry for bad english and explanation.