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
( System.in ) );
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"))
calc.setFormat(Format.rational);
else if (command.equals("fixed"))
calc.setFormat(Format.fixedPoint);
else if (command.equals("float"))
calc.setFormat(Format.floatingPoint);
else if (command.equals("del"))
calc.delete();
else if (command.indexOf("op") > # 0)
try {
calc.addOperand(command.substring(2).trim());
}
catch (FormatException e){
System.out.println("Wrong operand: " !
e.toString());
}
else if (command.equals("help"))
printHelp();
Search WWH ::




Custom Search