ExtendedParser extends BaseParser { protected final float readTerm() throws ParserException { skipWhitespaces(); float result = readFactor(); skipWhitespaces(); while (available() && (peek() == '*' || peek() == '/')) { if (pop() == '*') { skipWhitespaces(); result *= readFactor(); } else { skipWhitespaces(); result /= readFactor(); } skipWhitespaces(); } return result; } ExtendedParser(String toParse);   }
@Test public void testTerm() throws ParserException { ExtendedParser parser = new ExtendedParser("5 * 5"); assertEquals(25f, parser.readTerm(), 0.0001); parser = new ExtendedParser("1 * -1 * +3"); assertEquals(-3f, parser.readTerm(), 0.0001); parser = new ExtendedParser("10"); assertEquals(10f, parser.readTerm(), 0.0001); parser = new ExtendedParser("3 / -varname"); parser.variables.put("varname", 42f); assertEquals(3f / -42f, parser.readTerm(), 0.0001); parser = new ExtendedParser("varname / varname"); parser.variables.put("varname", 42f); assertEquals(1f, parser.readTerm(), 0.0001); parser = new ExtendedParser("var_name * 2"); parser.variables.put("var_name", 42f); assertEquals(84f, parser.readTerm(), 0.0001); }
@Test public void testInvalidTerms() { try { new ExtendedParser("))()()").readTerm(); fail("Expected invalid term error"); } catch (ParserException e) { } try { new ExtendedParser("(())").readTerm(); fail("Expected invalid term error"); } catch (ParserException e) { } try { new ExtendedParser("((a))").readTerm(); fail("Expected invalid term error"); } catch (ParserException e) { } try { new ExtendedParser("-*").readTerm(); fail("Expected invalid term error"); } catch (ParserException e) { } try { new ExtendedParser("-").readTerm(); fail("Expected invalid term error"); } catch (ParserException e) { } try { new ExtendedParser("*").readTerm(); fail("Expected invalid term error"); } catch (ParserException e) { } }