Implementation in Java: 4.1 Calculator
Implementation in Java: 4.1 Calculator
Implementation in Java: 4.1 Calculator
Implementation in Java
4.1 Calculator
We first consider how a simple calculator with the basic four arithmetic functions, as
illustrated in Figure 4-1, may be implemented. Most generic machines allow adding
11 to 13 to be accomplished via the buttons 1 3 + 1 1 = .
34
1 2 3 +
4 5 6 –
7 8 9 *
C 0 = /
For a simple implementation, we will initially not concern ourselves with the
nonessentials of external looks (e.g., keypad layout or casing specifics as in real
calculators), but instead concentrate on the core calculating engine. Enhancements
involving mechanisms for the user interface may be subsequently considered. This is
consistent with the software engineering principle of abstraction.
Conceptually, the core calculator engine may be viewed as being comprised of
registers to hold values, together with built-in operators such as addition and subtrac-
tion to manipulate such values. Having operations involving two operands, the calcu-
lator needs at least two registers.
Four arithmetic operations imply at least four operators. A compute operator is
required to get its execution started, together with a clear operator to prepare the
registers for new computations. These correspond to the equal and clear keys on a
calculator. Lastly, the digits form the basic input mechanism for numeric operands.
We would assume that the display operator will retrieve a value for display on the
calculator panel.
Object initialization may be easily accomplished via constructor methods. In
this case, a CalculatorEngine object is initialized via invoking the clear operator.
The resultant Java code skeleton for CalculatorEngine objects with this basic rep-
resentation is shown in Listing 4-1. Note that all operators easily correspond to
instance methods, as well as to buttons on the face on a conventional calculator.
Code represented by ellipses will be elaborated in due course.
class CalculatorEngine {
int value;
int keep; // two calculator registers
void add() { ... }
void subtract() { ... }
void multiply() { ... }
void divide() { ... }
void compute() { ... }
void clear() { ... }
void digit(int x) { ... }
int display() { ... }
CalculatorEngine() { clear(); }
}
Listing 4-1: CalculatorEngine skeleton.
void clear() {
value = 0;
keep = 0;
}
Implementation in Java 41
int display() {
return(value);
}
void digit(int x) {
value = value*10 + x;
}
While this method stands out amongst the other methods as it expects an inte-
ger parameter to indicate which numeric key was pushed, it can be circumvented by
using wrapper methods such as zero(), one(), two(), three(), ...nine().
void one() {
digit(1);
}
void two() {
digit(2);
}
...
char toDo;
void add() {
keep = value; // keep first operand
value = 0; // initialise and get ready for second operand
toDo = ’+’; // this is what we should do later
}
42 Object-Oriented Programming and Java
void subtract() {
keep = value; // keep first operand
value = 0; // initialise and get ready for second operand
toDo = ’-’; // this is what we should do later
}
Since all the binary operations have the same form, it is again natural to adopt
abstraction techniques to relocate common code in a binaryOperation() method:
Lastly, we conclude with the compute operation which provides the answer to
applying the operator in toDo on the operands value and keep.
void compute(){
if (toDo == '+')
value = keep + value;
else if (toDo == '-')
value = keep - value;
else if (toDo == '*')
value = keep * value;
else if (toDo == '/')
value = keep / value;
keep = 0;
}
creates an instance and associates it with the variable c. Subsequently, the code
sequence
c.digit(1);
c.digit(3);
c.add();
c.digit(1);
c.digit(1);
c.compute();
Implementation in Java 43
computes the value of the expression 13 + 11. For verification purposes, the Java
API (Application Program Interface) method System.out.println() may be used
to produce output on the screen:
System.out.println(c.display());
There is, however, a slight snag: the CalculatorEngine object instance is the
only object in existence, yet which object would send it messages to compute
expressions? Or even more fundamental, at the very commencement of program
execution when no objects existed, how was the first object created?
Java solves this issue through the introduction of class methods, which are
invoked with respect to the class they are associated with rather than object instan-
ces. More specifically, the body of the static method named main() is the first code
sequence to be executed. As such, the previous code sequence must be brought into
main() and rearranged as follows:
The various code fragments may be brought together within a class construct in
the file CalculatorEngine.java as shown in Listing 4-2.
class CalculatorEngine {
int value;
int keep; // two calculator registers
char toDo;
void compute() {
if (toDo == '+')
value = keep + value;
else if (toDo == '-')
value = keep - value;
else if (toDo == '*')
value = keep * value;
else if (toDo == '/')
value = keep / value;
keep = 0;
}
44 Object-Oriented Programming and Java
void clear() {
value = 0;
keep = 0;
}
void digit(int x) {
value = value*10 + x;
}
int display() {
return(value);
}
CalculatorEngine() { clear(); }
With the Java Development Kit (JDK) appropriately installed, it may be com-
piled via:
$ javac CalculatorEngine.java
where CalculatorEngine.java is the name of the file containing the Java source
and $ is the system’s command line prompt. Similarly, execution of the resultant
Java byte code may proceed via:
$ java CalculatorEngine
class CalculatorInput {
BufferedReader stream;
CalculatorEngine engine;
CalculatorInput(CalculatorEngine e) {
InputStreamReader input = new InputStreamReader(System.in);
stream = new BufferedReader(input) ;
engine = e;
}
Until these topics are discussed in Chapters 9 and 10, it is not harmful that at
present, they be taken by faith. The “throws Exception” signature suffix allows for
Java exceptions to be for the moment ignored. It is useful for modular and secure
programming methodology. It also suffices that the BufferedReader class facilitates
input, and that the readLine() method allows an input line to be read.
The new user interface class may be compiled via
$ javac CalculatorInput.java
This provides the added flexibility of arbitrary computations via keyboard input
sequences. The calculator display is indicated within square brackets “[ ]”:
$ java CalculatorInput
[0]1
[1]3
[13]+
[0]1
[1]1
[11]=
[24]
import java.awt.*;
import java.awt.event.*;
CalculatorEngine engine;
TextField display;
engine = e;
top = new Panel();
top.add(display = new TextField(20));
bottom = new Panel();
bottom.setLayout(new GridLayout(4,4));
bottom.add(b = new Button("1")); b.addActionListener(this);
bottom.add(b = new Button("2")); b.addActionListener(this);
bottom.add(b = new Button("3")); b.addActionListener(this);
bottom.add(b = new Button("+")); b.addActionListener(this);
bottom.add(b = new Button("4")); b.addActionListener(this);
bottom.add(b = new Button("5")); b.addActionListener(this);
bottom.add(b = new Button("6")); b.addActionListener(this);
bottom.add(b = new Button("-")); b.addActionListener(this);
bottom.add(b = new Button("7")); b.addActionListener(this);
bottom.add(b = new Button("8")); b.addActionListener(this);
bottom.add(b = new Button("9")); b.addActionListener(this);
bottom.add(b = new Button("*")); b.addActionListener(this);
bottom.add(b = new Button("C")); b.addActionListener(this);
bottom.add(b = new Button("0")); b.addActionListener(this);
bottom.add(b = new Button("=")); b.addActionListener(this);
bottom.add(b = new Button("/")); b.addActionListener(this);
setLayout(new BorderLayout());
add("North", top);
add("South", bottom) ;
addWindowListener(listener) ;
setSize(180, 160) ;
show();
}
public void actionPerformed(ActionEvent e) {
char c = e.getActionCommand().charAt(0);
if (c == '+') engine.add();
else if (c == '-') engine.subtract();
else if (c == '*') engine.multiply();
48 Object-Oriented Programming and Java
4.5 Summary
This chapter demonstrates Java syntax and semantics covered earlier in Chapter 3.
The calculator case study example shows how:
4.6 Exercises
1. The operators for CalculatorEngine are binary and require two operands.
How would unary operators that require one operand be incorporated?
Modify the CalculatorEngine class to add the following capabilities.
squareOf
factorial
2. Choose two interface characters most apt for squareOf and factorial
and incorporate the additional capability into the CalculatorInput class.
3. Rearrange the layout of the calculator panel in the CalculatorFrame class
to accommodate the new capabilities, and modify the appropriate event-
handlers to take advantage of these functions.
4. The CalculatorFrame class produces the result of 247 corresponding to
the key input sequence 1 3 + 1 1 = 7 . Explain the reason for this
observation, and suggest how it may be corrected.
TUGAS PEMROGRAMAN BERORIENTASI
OBJEK
KALKULATOR
OLEH:
FEMBI REKRISNA GRANDEA PUTRA
M0513019
JURUSAN INFORMATIKA
FAKULTAS MATEMATIKA DAN ILMU PENGETAHUAN ALAM
UNIVERSITAS SEBELAS MARET
SURAKARTA
PENDAHULUAN
Java adalah bahasa pemrograman yang dapat dijalankan di komputer atau di telepon
genggam. Java juga merupakan bahasa pemrograman tingkat tinggi yang berorientasi objek
(OOP) yaitu cara ampuh dalam pengorganisasian dan pengembangan perangkat lunak. Pada
OOP, program komputer sebagai kelompok objek yang saling berinteraksi. Deskripsi
singkat OOP adalah mengorganisasikan program sebagai kumpulan komponen yang disebut
dengan objek. Program java tersusun dari bagian-bagian yang disebut kelas. Kelas itu
sendiri terdiri atas metode-metode yang melakukan pekerjaan dan mengembalika n
informasi setelah melakukan tugasnya.
Para pemrogram Java banyak mengambil keuntungan dari kumpulan kelas di pustaka
kelas Java, yang disebut dengan Java Application Programming Interface (API). Kelas-kelas
ini diorganisasikan menjadi sekelompok yang disebut paket (package). Jadi ada dua hal
yang harus dipelajari dalam Java, yaitu mempelajari bahasa Java dan bagaimana
mempergunakan kelas pada Java API. Kelas merupakan satu-satunya cara menyatakan
bagian eksekusi program, tidak ada cara lain. Sedangkan pengertian API itu sendiri ialah
seperangkat fungsi standar yang disediakan oleh OS atau Bahasa. Dalam Java, API
dimasukkan ke dalam package-package yang sesuai dengan fungsinya.
Beberapa fungsi java yaitu java merupakan bahasa yang sederhana. Java dirancang
agar mudah dipelajari dan digunakan secara efektif. Java tidak menyediakan fitur-fitur rumit
bahasa pemrograman tingkat tinggi, serta banyak pekerjaan pemrograman yang mulanya
harus dilakukan manual, sekarang digantikan dikerjakan Java secara otomatis seperti
dealokasi memori.
PEMBAHASAN
if (c == '+') engine.add();
else if (c == '-') engine.subtract();
else if (c == '*') engine.multiply();
else if (c == '/') engine.divide();
else if (c >= '0' && c <= '9') engine.digit(c - '0');
else if (c == '=') engine.compute();
else if (c == 'c' || c == 'C') engine.clear();
char toDo;
void add(){
keep=value;
value=0;
toDo='+';
void subtract(){
keep=value;
value=0;
toDo='-';
void multiply(){
keep=value;
value=0;
toDo='*';
o Lalu operasi pemrosesan data (=) dilakukan dengan source code berikut:
void compute(){
if(toDo=='+')
value = keep + value;
else if(toDo=='-')
value = keep - value;
else if(toDo=='*')
value = keep * value;
else if(toDo=='/')
value = keep / value;
keep =0;
Kalkulator dengan Input Berbasis GUI
Untuk kalkulator berbasis GUI pertama-tama dimulai dengan membuat class
baru yaitu class CalculatorFrame, yang digunakan untuk membuat desain interface
sebuah kalkulator yang nantinya akan dihubungkan ke class CalculatorEngine yang
digunakan untuk operasi perhitungan sebuah kalkulator.
Lalu setelah membuat class untuk interface, langkah selanjutnya adalah
membuat interface untuk menginputkan angka serta jenis pengoperasiannya. Berikut
merupakan source code-nya:
CalculatorFrame(CalculatorEngine e) {
super("Calculator");
Panel top, bottom; Button b;
engine = e;
top = new Panel();
top.add(display = new TextField(20));
bottom = new Panel();
bottom.setLayout(new GridLayout(4,4));
bottom.add(b = new Button("1")); b.addActionListener(this);
bottom.add(b = new Button("2")); b.addActionListener(this);
bottom.add(b = new Button("3")); b.addActionListener(this);
bottom.add(b = new Button("+")); b.addActionListener(this);
bottom.add(b = new Button("4")); b.addActionListener(this);
bottom.add(b = new Button("5")); b.addActionListener(this);
bottom.add(b = new Button("6")); b.addActionListener(this);
bottom.add(b = new Button("-")); b.addActionListener(this);
bottom.add(b = new Button("7")); b.addActionListener(this);
bottom.add(b = new Button("8")); b.addActionListener(this);
bottom.add(b = new Button("9")); b.addActionListener(this);
bottom.add(b = new Button("*")); b.addActionListener(this);
bottom.add(b = new Button("C")); b.addActionListener(this);
bottom.add(b = new Button("0")); b.addActionListener(this);
bottom.add(b = new Button("=")); b.addActionListener(this);
bottom.add(b = new Button("/")); b.addActionListener(this);
setLayout(new BorderLayout());
add("North", top);
add("South", bottom) ;
addWindowListener(listener) ;
setSize(180, 160) ;
show();
}
char toDo;
void add(){
keep=value;
value=0;
toDo='+';
void subtract(){
keep=value;
value=0;
toDo='-';
void multiply(){
keep=value;
value=0;
toDo='*';
void divide(){
keep=value;
value=0;
toDo='/';
}
o Lalu operasi pemrosesan data (=) dilakukan dengan source code berikut:
void compute(){
if(toDo=='+')
value = keep + value;
else if(toDo=='-')
value = keep - value;
else if(toDo=='*')
value = keep * value;
else if(toDo=='/')
value = keep / value;
keep =0;