creating calculator using java
Post on 31-Oct-2014
26 Views
Preview:
DESCRIPTION
TRANSCRIPT
Creating Simple Calculator
OBJECT ORIENTED PROGRAMMINGFINAL PROJECT
Fiona Angelina© 2011
Step 1: Creating the Design
Step 2: Make Sure All Buttons is Working
• Concatting Numbers
Simplest Way of Concatting Number
• Treat the number as a String. Cast to Double when calculating.
• Pseudocode://Get text from textfield, put it into String s//Concat s with other number (0, 1, 2, …, 9)//Set textfield with s
Simplest Way of Concatting Number
• Code might look like this:String s = text.getText();s = s.concat(“1”);text.setText(s);
Step 2: Make Sure All Buttons is Working
• Clear button
Clearing TextField
• To clear textfield, simply set it with a new value. In this case, it is “0”.
• Code might look like this:text.setText(“0”);
Step 2: Make Sure All Buttons is Working
• Backspace button
Allowing Backspace
• Use method subSequence with start index = 0 and end index = length of string – 1.
• Don’t forget to convert the resulting CharSequence to String.
• Code might look like this:String s = text.getText();CharSequence res = s.subsequence(0, s.length() – 1);
text.setText(res.toString());
Step 3: Operations
Strategy To Make Operation Works
• Strategy:– Create two variables:• operator: to store the last operator• operand: to store the last operand
How Does It Work?
• 1: After finished concatting number, user clicks “+”.
This button is clicked
How Does It Work?
• 2: Identify if it is the first number that user enters or not. Assume it is the first number, simply put the operand and operator inside the variables.
operator = “+”
operand = 98
How Does It Work?
• 3: User concats another number, and press “*”.
This button is clicked
How Does It Work?
• 4: Identify if it is a first operand or not. Now it is not the first operand. Therefore you have to calculate a result.
How Does It Workoperator = “+”operand = 98 newNum = 6
operand = 104
operator = “*”operand = 104
CURRENT STATUS
How Does It Work?
• 5: Suppose user concats another number, and this time press “=“.
This button is clicked
How Does It Work?
• 6: When user enters “=“ instead of other kind of operators, you have to calculate the result, and reset all the variables.
How Does It Work?
operator = “*”operand = 104 newNum = 3
operand = 312Output the result to textfield
operand = null operator = null
CURRENT STATUS
Step 4: Playing with Memory
• Strategy:– Create 1 null variable to represent the memory.– M+ & M- : identify if it is the first memory. If it is,
store the current value. If not, increment/decrement with the previous value.
– MC : set the memory to null.– MR : set textfield with value inside memory.
top related