I can see that there are a lot of java calculators on here, so I hope it hasn't gotten too old. This is a basic 4-function calculator in java using the swing interface. I am positive that it is inefficient, so don't hold back or anything. Here's the code, leaving out the code auto-generated by Netbeans for the swing interface (though my the source file is here, if you need to look at it):
package CalcViewer;
/**
*
* @author wesrickey
*/
public class CalcView extends javax.swing.JFrame {
String expression = "";
String[] expressionArray;
String firstTerm;
String secondTerm;
double firstDoub;
double secondDoub;
boolean isResult = false;
/**
* Creates new form CalcView
*/
public CalcView() {
initComponents();
}
public double doCalc(char op) {
double result = 0;
// couldn't get the regex to work as one term, so this'll have to do for now
if (expression.contains("+")) {
expressionArray = expression.split("\\+");
} else if (expression.contains("-")) {
expressionArray = expression.split("-");
} else if (expression.contains("*")) {
expressionArray = expression.split("\\*");
} else if (expression.contains("/")) {
expressionArray = expression.split("/");
}
firstDoub = Double.parseDouble(expressionArray[0]);
secondDoub = Double.parseDouble(expressionArray[1]);
if (op == 'p') {
result = firstDoub + secondDoub;
} else if (op == 'm') {
result = firstDoub - secondDoub;
} else if (op == 't') {
result = firstDoub * secondDoub;
} else if (op == 'd') {
result = firstDoub / secondDoub;
}
isResult = true;
return result;
}
// same story as above with the regex not working for me
public boolean hasPattern(String input) {
if (input.contains("+")) {
return true;
} else if (input.contains("-")) {
return true;
} else if (input.contains("*")) {
return true;
} else if (input.contains("/")) {
return true;
} else return false;
}
(auto-generated layout code)
private void btnOneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOneActionPerformed
setFocusable(true);
if (isResult) {
isResult = false;
}
expression += "1";
textDisplay.setText(expression);
}//GEN-LAST:event_btnOneActionPerformed
private void btnTwoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTwoActionPerformed
if (isResult) {
isResult = false;
}
expression += "2";
textDisplay.setText(expression);
}//GEN-LAST:event_btnTwoActionPerformed
private void btnThreeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnThreeActionPerformed
if (isResult) {
isResult = false;
}
expression += "3";
textDisplay.setText(expression);
}//GEN-LAST:event_btnThreeActionPerformed
private void btnFourActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFourActionPerformed
if (isResult) {
isResult = false;
}
expression += "4";
textDisplay.setText(expression);
}//GEN-LAST:event_btnFourActionPerformed
private void btnFiveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFiveActionPerformed
if (isResult) {
isResult = false;
}
expression += "5";
textDisplay.setText(expression);
}//GEN-LAST:event_btnFiveActionPerformed
private void btnSixActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSixActionPerformed
if (isResult) {
isResult = false;
}
expression += "6";
textDisplay.setText(expression);
}//GEN-LAST:event_btnSixActionPerformed
private void btnSevenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSevenActionPerformed
expression += "7";
textDisplay.setText(expression);
}//GEN-LAST:event_btnSevenActionPerformed
private void btnEightActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEightActionPerformed
expression += "8";
textDisplay.setText(expression);
}//GEN-LAST:event_btnEightActionPerformed
private void btnNineActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNineActionPerformed
if (isResult) {
isResult = false;
}
expression += "9";
textDisplay.setText(expression);
}//GEN-LAST:event_btnNineActionPerformed
private void btnZeroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnZeroActionPerformed
if (isResult) {
isResult = false;
}
if (!expression.equals("0")) {
expression += "0";
}
textDisplay.setText(expression);
}//GEN-LAST:event_btnZeroActionPerformed
private void btnClearAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnClearAllActionPerformed
expression = "";
textDisplay.setText("0");
}//GEN-LAST:event_btnClearAllActionPerformed
private void btnPlusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPlusActionPerformed
if (!hasPattern(expression)) {
expression += "+";
}
}//GEN-LAST:event_btnPlusActionPerformed
private void btnSubtractActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSubtractActionPerformed
if (!hasPattern(expression)) {
expression += "-";
}
}//GEN-LAST:event_btnSubtractActionPerformed
private void btnMultiplyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnMultiplyActionPerformed
if (!hasPattern(expression)) {
expression += "*";
}
}//GEN-LAST:event_btnMultiplyActionPerformed
private void btnDivideActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDivideActionPerformed
if (!hasPattern(expression)) {
expression += "/";
}
}//GEN-LAST:event_btnDivideActionPerformed
private void btnEqualsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEqualsActionPerformed
double resultDoub;
String resultString;
// does the calculation base on the input operation
if (expression.contains("+")) {
resultDoub = doCalc('p');
} else if (expression.contains("-")) {
resultDoub = doCalc('m');
} else if (expression.contains("*")) {
resultDoub = doCalc('t');
} else if (expression.contains("/")) {
resultDoub = doCalc('d');
} else {
resultDoub = 0;
}
// sets result as a double if a double and an integer if an integer
// as opposed to before when everything displayed as a double
if (!(resultDoub % 1 == 0)) {
resultString = Double.toString(resultDoub);
} else {
int resultInt = (int)resultDoub;
resultString = Integer.toString(resultInt);
}
expression = resultString;
textDisplay.setText(resultString);
}//GEN-LAST:event_btnEqualsActionPerformed
private void btnDecimalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDecimalActionPerformed
expression += ".";
}//GEN-LAST:event_btnDecimalActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(CalcView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CalcView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CalcView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CalcView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new CalcView().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnClearAll;
private javax.swing.JButton btnClearEntry;
private javax.swing.JButton btnDecimal;
private javax.swing.JButton btnDivide;
private javax.swing.JButton btnEight;
private javax.swing.JButton btnEquals;
private javax.swing.JButton btnFive;
private javax.swing.JButton btnFour;
private javax.swing.JButton btnMultiply;
private javax.swing.JButton btnNine;
private javax.swing.JButton btnOne;
private javax.swing.JButton btnPlus;
private javax.swing.JButton btnPositiveNegative;
private javax.swing.JButton btnSeven;
private javax.swing.JButton btnSix;
private javax.swing.JButton btnSubtract;
private javax.swing.JButton btnThree;
private javax.swing.JButton btnTwo;
private javax.swing.JButton btnZero;
private javax.swing.JTextField textDisplay;
// End of variables declaration//GEN-END:variables
}
One of the main flaws that I'm aware of is my hasPattern();
method. I had to use that to check if the expression has an operator in it, since I could not for the life of me get the regular expression for that pattern to work, so I improvised.
1 Answer 1
General code style
positives
- you respect java naming conventions
- you don't use static methods
- at least one comment tells why the code is the way it is.
negatives
- you inherit from
JFrame
without changing its behavior. - you have a lot of duplicated code.
- you use
double
(and notBigDecimal
) which has accuracy issues. - most comments repeat what the codes does an are therefore obsolete.
- some comments "structure" the method.
- you create a "structured string" for further processing which needs parsing afterwards.
- you declare the member variables at the bottom of the class, they should be on top.
suggestions
structured string
As long as you plan to handle 2 numbers only create an array of StringBuilder
variables with size of 2.
create a "counter" that is toggled between 0
and 1
when an operator button is clicket. Convert the numberst to BigIntegers before passing them to the calculation method.
store the operator in a variable of its own and pass it along with the numbers as separate parameter to the calculation method. This way you don't have to deal with regexp...
code duplication
The suggestions above will eliminate most of your if/else
cascades.
In your main you catch each exception type individually but the action taken is the same for all. Replace all the catch
blocks with a single one catching a more general exception type, preferably Exception