0

For implementation specific reasons, I have to use Java 1.2. I am trying to parse a String object with only numbers (I replace variables beforehand to abstract that step) and operators (PEDMAS). I have found a lot of libraries that do this well, but unfortunately nothing that is compatible with Java 1.2 (Even with fiddling, all of them are dependent on things like generics). Obviously I'm capable of making this myself, but I would certainly prefer to not remake the wheel. Are there any libraries that I just haven't found yet that could do this for me? Thanks.

(Requirements: Binary operators and parentheses)

EDIT: As requested, some examples of input and output:

  • "(10 / 5) + 4.5 - (8)" would give you -1.5
  • "(1/3) * 4" would give you 1.3333333...
  • "5^3 + 4 * 2" would give you 133
  • "-10 + 5" would give you -5

Hopefully that makes sense.

Joel Gallant
  • 315
  • 4
  • 21

1 Answers1

2

You can write your own recursive descent parser. This Java implementation uses StreamTokenizer, available since 1.0, but you'll have to substitute int constants for the enum tokens and ignore tokenIs(Symbol.WORD) for function identifiers.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • Small problem I'm encountering... It uses the method `Enum.valueOf(class, String)`, and because `Function` is no longer an enum, it cannot be used. (Function does not extend Enum) _found on line 276_. – Joel Gallant Nov 26 '12 at 04:25
  • Also, it appears I cannot access the Enum class (Java ME). Is there a way to replicate the function of this method without Enum? – Joel Gallant Nov 26 '12 at 04:27
  • Unless you need functions, just eliminate handling `Symbol.WORD` in `factor()`. If you do, I think Apache Commons had a pre-1.5 alternative. – trashgod Nov 26 '12 at 10:48