diff --git a/src/main/java/dev/sillyangel/calc/utils b/src/main/java/dev/sillyangel/calc/utils new file mode 100644 index 0000000..94844a3 --- /dev/null +++ b/src/main/java/dev/sillyangel/calc/utils @@ -0,0 +1,104 @@ +utils.java +package dev.sillyangel.calc; + +public class utils { + // private double result; + // private boolean resultVisible; + private Calculator ci; + public utils(Calculator ci) { + System.out.printf(""); + this.ci = ci; + } + + public void reciprocal() { + String tmp = ci.display.getText(); + if (tmp == null || tmp.isEmpty()) { + return; + } + try { + double value = Double.parseDouble(tmp); + if (value != 0) { + ci.result = 1.0 / value; + ci.display.setText("" + ci.result); + ci.resultVisible = true; + } else { + ci.display.setText("Error: Div by Zero"); + ci.resultVisible = false; + } + } catch (NumberFormatException e) { + ci.display.setText("Error: Invalid Input"); + ci.resultVisible = false; + } + } + + public void clearAll() { + ci.display.setText(""); + ci.operand1 = ""; + ci.operand2 = ""; + ci.operator = ""; + } + + public void square() { + String tmp = ci.display.getText(); + if (tmp == null || tmp.isEmpty()) return; + double value = Double.parseDouble(tmp); + ci.result = value * value; + ci.display.setText("" + ci.result); + ci.resultVisible = true; + } + + public void squareRoot() { + String tmp = ci.display.getText(); + if (tmp == null || tmp.isEmpty()) return; + double value = Double.parseDouble(tmp); + if (value >= 0) { + ci.result = Math.sqrt(value); + ci.display.setText("" + ci.result); + ci.resultVisible = true; + } + } + + public void backspace() { + String tmp = ci.display.getText(); + if (tmp.length()>1) // if there is more than 1 character + ci.display.setText( tmp.substring(0, tmp.length()-1) ); + else // otherwise just make display empty + ci.display.setText(""); + } + + public void math() { + ci.operand2 = ci.display.getText(); + double op1 = Double.parseDouble(ci.operand1); + double op2 = Double.parseDouble(ci.operand2); + + if ("+".equals(ci.operator)) { + ci.result = op1+op2; + } else if ("-".equals(ci.operator)) { + ci.result = op1-op2; + } else if ("*".equals(ci.operator)) { + ci.result = op1*op2; + } else if ("/".equals(ci.operator)) { + ci.result = op1/op2; + } else if ("%".equals(ci.operator)) { + ci.result = op1 % op2; + } else { + ci.result = op2; + System.out.println("Op: " + op1); + System.out.println("Op2: " + op2); + } + + // Save calculation to history + if (!ci.operator.isEmpty()) { + String calculation = ci.operand1 + " " + ci.operator + " " + ci.operand2 + " = " + ci.result; + ci.history.saveToHistory(calculation); + } + + ci.operator = ""; + ci.operand1 = ""; + ci.operand2 = ""; + + resultVisible = true; + display.setText(""+result); + saveToUndoStack(""+result); + } +} \ No newline at end of file