Java Reference
In-Depth Information
Class Command implements the command line interpreter. It has an
attribute ( calc ) that links the interpreter to an instance of the Calculator
class. The method nextCommand() reads a command and process it. If a valid
command is recognized the corresponding method of the calculator is
invoked. The readLine() method of the BufferedReader class can throw an
IOException when some problem with the input stream occurs. We handle
this exception enclosing all the method's statements in a try
catch block.
When an IOException is thrown we assume that there is no command to
process, therefore all the statements are skipped and the method returns.
public class Command {
Calculator calc # new Calculator();
BufferedReader lineReader # new BufferedReader(
new InputStreamReader
( ) );
boolean nextCommand() {
System.out.print("\n[" ! calc.getFormat().getName() ! ","
! calc.firstOperand() ! ", "
! calc.secondOperand() ! "] >");
try {
// reads the command from the keyboard
String command # lineReader.readLine();
// executes an arithmetical operation
if (command.equals(" ! ")) calc.add();
else if (command.equals("-")) calc.subtract();
else if (command.equals("*")) calc.multiply();
else if (command.equals("/")) calc.divide();
else if (command.equals("rat"))
else if (command.equals("fixed"))
else if (command.equals("float"))
else if (command.equals("del"))
else if (command.indexOf("op") > # 0)
try {
catch (FormatException e){
System.out.println("Wrong operand: " !
else if (command.equals("help"))
Search WWH ::

Custom Search