Calculator
RepositoryIn this project I worked on desktop application development. I used the JavaFX framework in combination with classic Java 23. I had no previous experience with desktop development in Java. This project also helped me a lot in developing my CSS skills.
HelloApplication Java Class
Here is a snippet of my HelloApplication class. This class defines the basic elements and layout of the calculator. The rest of the class is available on the GitHub repository.
1//Operator Button Actions
2Map<Button, String> operatorButtons = new HashMap<>();
3operatorButtons.put(addBtn, "+");
4operatorButtons.put(subtractBtn, "-");
5operatorButtons.put(multiplyBtn, "*");
6operatorButtons.put(divideBtn, "/");
7
8operatorButtons.forEach((button, operator) ->
9 button.setOnAction(e -> {
10 if (!calc.currentNumber.isEmpty()) {
11 calc.allNumbers.add(calc.currentNumber);
12 calc.currentNumber = "";
13 calc.allOperations.add(operator);
14 } else if (!calc.allOperations.isEmpty()) {
15 calc.allOperations.set(calc.allOperations.size() - 1, operator);
16 } else {
17 calc.allOperations.add(operator);
18 }
19 equationLabel.setText(calc.getCurrentEquation());
20 })
21);
22
23//Negate button
24negateBtn.setOnAction(e -> {
25 if (calc.currentNumber.isEmpty()) {
26 calc.currentNumber += "-";
27 } else {
28 if (calc.currentNumber.charAt(0) == '-') {
29 calc.currentNumber = calc.currentNumber.substring(1);
30 } else {
31 calc.currentNumber = "-" + calc.currentNumber;
32 }
33 }
34 output.setText(calc.getCurrentNumber());
35 equationLabel.setText(calc.getCurrentEquation());
36});Calculator Java Class
Here is an excerpt from my Calculator class. This class handles all the logic related to the calculations. The rest of the class is available on the GitHub repository.
1public void calculateAll() {
2 if (correctNumberAndOperationAmount()) {
3 try {
4 String[] parts = currentEquation.split(" ");
5 System.out.println("Parts: " + Arrays.toString(parts));
6
7 for (int i = 1; i < parts.length; i++) {
8 if (parts[i].equals("*") || parts[i].equals("/")) {
9 double prevNum = Double.parseDouble(parts[i - 1]);
10 double nextNum = Double.parseDouble(parts[i + 1]);
11 double resultPart = 0;
12
13 if (parts[i].equals("*")) {
14 resultPart = prevNum * nextNum;
15 } else if (parts[i].equals("/")) {
16 if (nextNum == 0) {
17 result = "#ERROR#";
18 return;
19 }
20 resultPart = prevNum / nextNum;
21 }
22
23 parts[i - 1] = String.valueOf(resultPart);
24 for (int j = i; j < parts.length - 2; j++) {
25 parts[j] = parts[j + 2];
26 }
27 parts = Arrays.copyOf(parts, parts.length - 2);
28 i--;
29 }
30 }
31 // cut off
32 } else {
33 result = "#ERROR#";
34 }
35}Try it out yourself!
DownloadIf you want to try this app out for yourself, click on the download button and install Calculator v02.jar from GitHub. In order for this app to work, you will need to have Java 23 or newer installed.
Video Demonstration
This video requires optional cookies (YouTube).