HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Is this code for a calculator efficient?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thisefficientforcodecalculator

Problem

```
package standardcalculator;

/**
*
* @author BSK
*/
public class calculator2 extends javax.swing.JFrame {
private String input="";//We have nothing to display on the screen,if we dont do this creates the problem of displaying the null.
private String firstOperand="0"; //Standard firstOperand.
private String previousResult = "";//for storing the previous result.
private String operation="noOperation";//initialy noOperation.
/**
* Creates new form calculator2
*/
public calculator2() {
initComponents();
}
private void commonAction(String inpt){
input += inpt;
displayscreen.setText(input);
}
private boolean isFirstOperand(){
return firstOperand.equals("0");
}
private void button1ActionPerformed(java.awt.event.ActionEvent evt) {
commonAction("1");
}

private void button2ActionPerformed(java.awt.event.ActionEvent evt) {
commonAction("2");
}

private void button3ActionPerformed(java.awt.event.ActionEvent evt) {
commonAction("3");
}

private void button4ActionPerformed(java.awt.event.ActionEvent evt) {
commonAction("4");
}

private void button5ActionPerformed(java.awt.event.ActionEvent evt) {
commonAction("5");
}

private void button6ActionPerformed(java.awt.event.ActionEvent evt) {
commonAction("6");
}

private void button7ActionPerformed(java.awt.event.ActionEvent evt) {
commonAction("7");
}

private void

Solution

Step 1 : Reduce different event handlers which performs almost same task.

How:

Step 1.1: The button click events (button1ActionPerformed and similar others) which are calling the commonAction method, delete all except 1 method.

Step 1.2: Analyze the event variable of the event you kept. It should have information about the button, get the text of the button and pass it as a parameter of commonAction method

step 1.3: For the other button's click events, attach the same event for all of them.

Context

StackExchange Code Review Q#55097, answer score: 5

Revisions (0)

No revisions yet.