From 02165bd184f143968a277f67ad38c795700c1b1c Mon Sep 17 00:00:00 2001 From: Alex Date: Thu, 14 Mar 2024 05:27:35 +0100 Subject: [PATCH] finished the ability to type in numbers with the keyboard. --- .../net/marakaner/calc/CalcController.java | 39 ++++++++++--------- 1 file changed, 20 insertions(+), 19 deletions(-) diff --git a/src/main/java/net/marakaner/calc/CalcController.java b/src/main/java/net/marakaner/calc/CalcController.java index 58531ee..b0e881d 100644 --- a/src/main/java/net/marakaner/calc/CalcController.java +++ b/src/main/java/net/marakaner/calc/CalcController.java @@ -19,13 +19,8 @@ public class CalcController implements Initializable { private String lastChar = ""; private void addChar(String next, boolean spacing) { - if(lastChar.equals("(") || lastChar.equals(")")) { - if(!next.matches("\\d")) { - return; - } - } - - this.label.setText((spacing ? " " : "") + next + (spacing ? " " : "")); + lastChar = next; + this.label.setText(this.label.getText() + (spacing ? " " : "") + next + (spacing ? " " : "")); } private void addChar(String next) { @@ -100,18 +95,7 @@ public class CalcController implements Initializable { } public void onSum(ActionEvent actionEvent) { - Expression expression = new ExpressionBuilder(this.label.getText()).build(); - - double result = expression.evaluate(); - - System.out.println(result % 1); - - if(result % 1.0 == 0.0) { - int intResult = (int) result; - this.label.setText("" + intResult); - } else { - this.label.setText("" + result); - } + calculate(); } public void onPlus(ActionEvent actionEvent) { @@ -128,10 +112,27 @@ public class CalcController implements Initializable { addChar(keyEvent.getText()); } else if(keyEvent.getText().matches("[+\\-*/]")) { addChar(keyEvent.getText(), true); + } else if(keyEvent.getCode() == KeyCode.ENTER) { + calculate(); } }); } + private void calculate() { + Expression expression = new ExpressionBuilder(this.label.getText()).build(); + + double result = expression.evaluate(); + + System.out.println(result % 1); + + if(result % 1.0 == 0.0) { + int intResult = (int) result; + this.label.setText("" + intResult); + } else { + this.label.setText("" + result); + } + } + public void onKeyPressed(KeyEvent keyEvent) { System.out.println(keyEvent.getText()); }