View Javadoc
1   package calculator.command;
2   
3   import calculator.Calculator;
4   import calculator.Expression;
5   import calculator.antlr.Parser;
6   import calculator.atoms.Atom;
7   import calculator.Notation;
8   import java.util.logging.Level;
9   import java.util.logging.Logger;
10  
11  public class EvalCommand implements CLICommand {
12  
13  	private static final Logger LOGGER = Logger.getLogger(EvalCommand.class.getName());
14  
15  	@Override
16  	public boolean execute(String args) {
17  		try {
18  			if (args == null || args.trim().isEmpty()) {
19  				LOGGER.warning("No expression provided.");
20  				return true;
21  			}
22  
23  			Parser parser = new Parser();
24  			Expression e = parser.parse(args);
25  
26  			Calculator c = new Calculator();
27  			Atom result = c.eval(e);
28  
29  			System.out.println(args + " = " + c.format(result, Notation.INFIX));
30  
31  		} catch (IllegalArgumentException e) {
32  			LOGGER.log(Level.SEVERE, "Invalid expression: " + e.getMessage());
33  		} catch (Exception e) {
34  			LOGGER.log(Level.SEVERE, "Error evaluating expression: {0}", e.getMessage());
35  		}
36  		return true;
37  	}
38  }