View Javadoc
1   package calculator;
2   
3   import calculator.command.CLICommand;
4   import calculator.command.EvalCommand;
5   import calculator.command.ExitCommand;
6   import calculator.command.HelpCommand;
7   
8   import java.util.HashMap;
9   import java.util.Map;
10  import java.util.Scanner;
11  
12  import calculator.atoms.Real;
13  import calculator.operations.*;
14  
15  /**
16   * A very simple calculator in Java
17   * University of Mons - UMONS
18   * Software Engineering Lab
19   * Faculty of Sciences
20   *
21   * @author tommens
22   */
23  public class Main {
24  
25  	/**
26  	 * This is the main method of the application.
27  	 * It provides examples of how to use it to construct and evaluate arithmetic
28  	 * expressions.
29  	 *
30  	 * @param args Command-line parameters are not used in this version
31  	 */
32  	public static void main(String[] args) {
33  		// Commands registration
34          Map<String, CLICommand> commands = new HashMap<>();
35          commands.put("help", new HelpCommand());
36          commands.put("exit", new ExitCommand());
37          commands.put("eval", new EvalCommand());
38  
39  		Scanner scanner = new Scanner(System.in);
40  		System.out.println("Welcome to the Calculator! Type 'help' for assistance.");
41  		
42  		boolean running = true;
43          while (running) {
44              System.out.print("calc> ");
45              String input = scanner.nextLine().trim();  // Trim input to handle extra spaces
46              
47              if (input.isEmpty()) continue;
48              
49              String[] parts = input.split(" ", 2);  // Split to get command (first word)
50              String commandName = parts[0].toLowerCase(); // Command names are case-insensitive
51              String arguments = parts.length > 1 ? parts[1] : "";  // The rest of the input is considered as arguments
52              
53              CLICommand command = commands.get(commandName);  // = null if command not found (or not eval at the beginning of the input)
54              
55              if (command != null) {
56                  running = command.execute(arguments);
57              } else {
58                  CLICommand defaultEval = commands.get("eval");
59                  running = defaultEval.execute(input);
60              }
61          }
62          scanner.close();
63  	}
64  
65  }