Java Scientific Calculator Program (Source Code, swing, switch)
In mathematics and science, precision and versatility are paramount. Whether you're a student tackling complex equations, a scientist analyzing data, or an engineer designing intricate systems, having a robust scientific calculator can make all the difference.
While commercial scientific calculators offer an array of functions, building your own scientific calculator in Java not only enhances your programming skills but also allows you to customize it to your specific needs.
In this tutorial, we will create a scientific calculator in Java using swing GUI and switch case. These programs are designed for both beginners and intermediate programmers.
-
The first program (using swing) provides a more user-friendly and visually appealing calculator with a GUI.
-
On the other hand, the second program (using switch) is a command-line calculator that requires users to input values and operators through text and receive output in the console/terminal.
The choice between these two approaches depends on the intended use and audience for the calculator. GUI-based calculators are typically more user-friendly and suitable for general users, while command-line calculators can be preferred by developers or those who prefer text-based interfaces.
Java Concepts Used:
Scientific Calculator in Java Using Swing
Below is an example of implementing a scientific calculator program in Java using Swing GUI components. You can copy or download this source code for free and use easily.
Code
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.util.EmptyStackException;
import java.util.Stack;
import java.lang.Math;
public class ScientificCalculator {
private JFrame frame;
private JTextField display;
private String input = "";
private Stack<Double> memory = new Stack<>();
public ScientificCalculator() {
frame = new JFrame("Scientific Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLayout(new BorderLayout());
display = new JTextField();
display.setFont(new Font("Arial", Font.PLAIN, 20));
display.setEditable(false);
frame.add(display, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(6, 5));
String[] buttons = {
"7", "8", "9", "/", "sqrt",
"4", "5", "6", "*", "x^2",
"1", "2", "3", "-", "x^y",
"0", ".", "+/-", "+", "=",
"sin", "cos", "tan", "log", "ln"
};
for (String button : buttons) {
JButton btn = new JButton(button);
btn.setFont(new Font("Arial", Font.PLAIN, 18));
btn.addActionListener(new ButtonClickListener());
buttonPanel.add(btn);
}
frame.add(buttonPanel, BorderLayout.CENTER);
frame.setVisible(true);
}
private class ButtonClickListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if ("0123456789.".contains(command)) {
input += command;
} else if ("+-*/".contains(command)) {
input += " " + command + " ";
} else if ("sqrt x^2 x^y sin cos tan log ln".contains(command)) {
input = command + "(" + input + ")";
} else if ("=".equals(command)) {
try {
input = evaluateExpression(input);
} catch (ArithmeticException ex) {
input = "Error";
}
} else if ("+/-".equals(command)) {
input = negateInput(input);
}
display.setText(input);
}
private String evaluateExpression(String expression) {
String result = "";
try {
String[] parts = expression.split(" ");
Stack<String> operators = new Stack<>();
Stack<Double> values = new Stack<>();
for (String part : parts) {
if ("+-*/sqrtx^2x^ysincostanlogln".contains(part)) {
operators.push(part);
} else {
values.push(Double.parseDouble(part));
}
while (!operators.isEmpty() && values.size() >= 2) {
String operator = operators.pop();
double b = values.pop();
double a = values.pop();
double res = calculate(a, b, operator);
values.push(res);
}
}
DecimalFormat df = new DecimalFormat("#.##########");
result = df.format(values.pop());
} catch (NumberFormatException | EmptyStackException e) {
result = "Error";
}
return result;
}
private double calculate(double a, double b, String operator) {
switch (operator) {
case "+":
return a + b;
case "-":
return a - b;
case "*":
return a * b;
case "/":
if (b == 0) throw new ArithmeticException("Division by zero");
return a / b;
case "sqrt":
if (a < 0) throw new ArithmeticException("Square root of negative number");
return Math.sqrt(a);
case "x^2":
return a * a;
case "x^y":
return Math.pow(a, b);
case "sin":
return Math.sin(Math.toRadians(a));
case "cos":
return Math.cos(Math.toRadians(a));
case "tan":
return Math.tan(Math.toRadians(a));
case "log":
if (a <= 0 || b <= 0 || a == 1) throw new ArithmeticException("Invalid logarithm");
return Math.log(b) / Math.log(a);
case "ln":
if (a <= 0) throw new ArithmeticException("Invalid natural logarithm");
return Math.log(a);
default:
throw new IllegalArgumentException("Invalid operator: " + operator);
}
}
private String negateInput(String input) {
if (input.isEmpty()) return input;
String[] parts = input.split(" ");
int lastIndex = parts.length - 1;
String lastPart = parts[lastIndex];
if (!lastPart.isEmpty() && Character.isDigit(lastPart.charAt(0))) {
if (lastPart.charAt(0) == '-') {
parts[lastIndex] = lastPart.substring(1);
} else {
parts[lastIndex] = "-" + lastPart;
}
return String.join(" ", parts);
} else {
return input;
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(ScientificCalculator::new);
}
}
Output
When you run the Java scientific calculator source code into your IDE like NetBeans or Eclipse, it will show a GUI-based calculator that performs all the essential operations.
Explanation
This Java program for scientific calculator using Swing allows users to perform arithmetic operations like addition, subtraction, multiplication, and division, as well as scientific functions like square root, reciprocal, percentage, trigonometric functions (sin, cos, tan) and logarithmic functions (log, ln).
The calculator provides a user-friendly interface for input and displays the result in a text field. It handles button clicks, performs calculations, and updates the display accordingly.
To run the program, compile the code and execute the ScientificCalculator class. The GUI calculator window will appear, and you can interact with it by clicking on the buttons to input numbers and perform operations. The calculator evaluates expressions and displays the results in real-time as you click the "=" button.
Source Code for Java Scientific Calculator Using Switch
Creating a comprehensive scientific calculator program in Java using switch-case statements allows for a structured and easily expandable design.
Below is an advanced example that includes basic arithmetic operations, trigonometric functions (sine, cosine, tangent), logarithmic functions (logarithm and natural logarithm), square root, power functions, memory storage, and more.
Code
import java.util.Scanner;
public class ScientificCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double result = 0;
boolean exit = false;
boolean newCalculation = true;
while (!exit) {
if (newCalculation) {
System.out.println("Scientific Calculator Menu:");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.println("5. Square Root");
System.out.println("6. Exponentiation");
System.out.println("7. Sine");
System.out.println("8. Cosine");
System.out.println("9. Tangent");
System.out.println("10. Logarithm (base 10)");
System.out.println("11. Natural Logarithm (ln)");
System.out.println("12. Memory Operations");
System.out.println("13. Exit");
System.out.print("Select an operation (1-13): ");
} else {
System.out.println("Result: " + result);
System.out.print("Select an operation (1-13 or 0 for new calculation): ");
}
int choice = scanner.nextInt();
double operand;
switch (choice) {
case 0:
newCalculation = true;
break;
case 1:
System.out.print("Enter the number to add: ");
operand = scanner.nextDouble();
result += operand;
newCalculation = false;
break;
case 2:
System.out.print("Enter the number to subtract: ");
operand = scanner.nextDouble();
result -= operand;
newCalculation = false;
break;
case 3:
System.out.print("Enter the number to multiply by: ");
operand = scanner.nextDouble();
result *= operand;
newCalculation = false;
break;
case 4:
System.out.print("Enter the number to divide by: ");
operand = scanner.nextDouble();
if (operand != 0) {
result /= operand;
} else {
System.out.println("Error: Division by zero.");
}
newCalculation = false;
break;
case 5:
result = Math.sqrt(result);
newCalculation = false;
break;
case 6:
System.out.print("Enter the exponent: ");
operand = scanner.nextDouble();
result = Math.pow(result, operand);
newCalculation = false;
break;
case 7:
result = Math.sin(result);
newCalculation = false;
break;
case 8:
result = Math.cos(result);
newCalculation = false;
break;
case 9:
result = Math.tan(result);
newCalculation = false;
break;
case 10:
if (result > 0) {
result = Math.log10(result);
} else {
System.out.println("Error: Invalid input for logarithm.");
}
newCalculation = false;
break;
case 11:
if (result > 0) {
result = Math.log(result);
} else {
System.out.println("Error: Invalid input for natural logarithm.");
}
newCalculation = false;
break;
case 12:
System.out.println("Memory Menu:");
System.out.println("1. Store result in memory");
System.out.println("2. Recall memory");
System.out.println("3. Clear memory");
System.out.print("Select a memory operation (1-3): ");
int memoryChoice = scanner.nextInt();
switch (memoryChoice) {
case 1:
memory = result;
break;
case 2:
result = memory;
break;
case 3:
memory = 0;
break;
default:
System.out.println("Invalid memory operation.");
break;
}
break;
case 13:
exit = true;
break;
default:
System.out.println("Invalid choice.");
break;
}
}
System.out.println("Calculator closed.");
}
}
Output
Scientific Calculator Menu:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Square Root
6. Exponentiation
7. Sine
8. Cosine
9. Tangent
10. Logarithm (base 10)
11. Natural Logarithm (ln)
12. Memory Operations
13. Exit
Select an operation (1-13): 1
Enter the number to add: 5
Result: 5.0
Select an operation (1-13 or 0 for new calculation): 3
Enter the number to multiply by: 2
Result: 10.0
Select an operation (1-13 or 0 for new calculation): 7
Result: -0.5440211108893699
Select an operation (1-13 or 0 for new calculation): 12
Memory Menu:
1. Store result in memory
2. Recall memory
3. Clear memory
Select a memory operation (1-3): 1
Select an operation (1-13 or 0 for new calculation): 0
Scientific Calculator Menu:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Square Root
6. Exponentiation
7. Sine
8. Cosine
9. Tangent
10. Logarithm (base 10)
11. Natural Logarithm (ln)
12. Memory Operations
13. Exit
Select an operation (1-13 or 0 for new calculation): 2
Enter the number to subtract: 3
Result: 7.0
Select an operation (1-13 or 0 for new calculation): 13
Calculator closed.
Explanation
This Java program implements a scientific calculator with various mathematical functions using switch-case statements for user input.
You can select operations from the menu and perform calculations, including basic arithmetic, trigonometric functions, logarithmic functions, power functions, and memory operations. The program also handles division by zero and invalid inputs.
Learn Next: