A console (aka console user interface, aka cui, aka read-execute-print loop, aka repl) is a simple command-line user interface. At its heart is the read-execute-print loop:
while(more)
try
print prompt
read command
execute command
print result
catch exceptions
Here's a simple reusable partial implementation:
Complete the repl method.
Notes
1. Our console distinguishes between two types of errors: user errors (represented by UserError exceptions) and system errors (represented by all other types of exceptions). When either type of exception is thrown we catch it, print the error message it contains, print a stack trace if the verbose flag is true, and quit if it's a system error. The idea being that something out of the user's control is wrong, out-of-memory for example.
2. Console is an abstract class. The execute method must be implemented in any concrete subclass.
3. Place Console is a package called cui that is outside of your lab1 package. This way it'll be easier to reuse.
Complete the extension of Console called MathConsole. Here's a sample interactive session:
-> add 2 3 4 5 6
20.0
-> mul 4 4 4 4
256.0
-> sub
Provide at least 1 argument
-> sub 10
10
-> sub 10 3 2 1
4.0
-> div 5 3 .5
3.3333333333333335
-> div 6 2 x
Arguments must be numbers
-> div 20 5 0
No division by 0
-> zip 2 3 4
Unrecognized operator:zip
-> quit
bye
Notes
1. Add, mul, sub, and div are the only operators our math console knows how to execute (for now). These can take any positive number of inputs of type Double.
2. All of the errors in the session were user errors that didn't cause the console to quit. Only the quit command or system errors can do this.
3. Consider using the split method of the String class:
val tokens = cmmd.split("\\s+") // = array of space-separated substrings of cmmd
3. Your implementation of execute should use the match/case expression.
4. To start a Scala program we need a static main method, but we can't declare static methods in Scala. Instead we can declare objects (which are static) containing a main method. In our code the declared object is also called Console. A declared object with the same name as a class is called a companion object.