Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 16

scientific-calculator-using-applet-in-java

import java.applet.*;
import java.awt.event.*;
import java.awt.*;
public class publiccalculator extends Applet implements ActionListener{

Label lblcasio = new Label("CASIO");


Label lblfx = new Label("fx-8265 PLUS");
Label lblnatural = new Label("NATURAL - V.P.A.M");

TextField txtfield1 = new TextField(30);

Button abs = new Button("Abs");


Button X2 = new Button("X^2");
Button X3 = new Button("X^3");
Button log = new Button("log");
Button sqrt = new Button("/---");

Button sin = new Button("sin");


Button cos = new Button("cos");
Button tan = new Button("tan");
Button pie = new Button("π");
Button E = new Button("E");

Button seven = new Button("7");


Button eight = new Button("8");
Button nine = new Button("9");
Button DEL = new Button("DEL");
Button AC = new Button("AC/CLEAR");

Button four = new Button("4");


Button five = new Button("5");
Button six = new Button("6");
Button multiply = new Button("X");
Button subtract = new Button("-");

Button one = new Button("1");


Button two = new Button("2");
Button three = new Button("3");
Button plus = new Button("+");
Button dive = new Button("/");

Button zero = new Button("0");


Button equals = new Button("=");
Button dot = new Button(".");
Button round = new Button("RND");

public void init(){

setLayout(null);
resize(500,400);

Font myCasio= new Font("Serif",Font.BOLD,18);


Font myFX= new Font("Serif",Font.BOLD,18);
Font myNatural = new Font("Serif",Font.BOLD,15);
lblcasio.setFont(myCasio);
lblfx.setFont(myFX);
lblnatural.setFont(myNatural);

add(lblcasio);
add(lblfx);
add(lblnatural);

add(txtfield1);

add(abs);
add(X2);
add(X3);
add(log);
add(sqrt);

add(sin);
add(cos);
add(tan);
add(pie);
add(E);

add(seven);
add(eight);
add(nine);
add(DEL);
add(AC);

add(four);
add(five);
add(six);
add(multiply);
add(subtract);

add(one);
add(two);
add(three);
add(plus);
add(dive);

add(zero);
add(equals);
add(dot);
add(round);

lblcasio.setBounds(60,0,100,20);
lblfx.setBounds(350,0,150,20);
lblnatural.setBounds(160,25,200,20);
txtfield1.setBounds(100,50,240,20);

abs.setBounds(100,75,35,35);
X2.setBounds(150,75,35,35);
X3.setBounds(200,75,35,35);
log.setBounds(250,75,35,35);
sqrt.setBounds(300,75,35,35);

sin.setBounds(100,120,35,35);
cos.setBounds(150,120,35,35);
tan.setBounds(200,120,35,35);
pie.setBounds(250,120,35,35);
E.setBounds(300,120,35,35);

seven.setBounds(100,165,35,35);
eight.setBounds(150,165,35,35);
nine.setBounds(200,165,35,35);
AC.setBounds(250,165,85,35);

four.setBounds(100,210,35,35);
five.setBounds(150,210,35,35);
six.setBounds(200,210,35,35);
multiply.setBounds(250,210,35,35);
subtract.setBounds(300,210,35,35);

one.setBounds(100,255,35,35);
two.setBounds(150,255,35,35);
three.setBounds(200,255,35,35);
plus.setBounds(250,255,35,35);
dive.setBounds(300,255,35,35);

zero.setBounds(100,300,35,35);
equals.setBounds(150,300,85,35);
dot.setBounds(250,300,35,35);
round.setBounds(300,300,35,35);

equals.addActionListener(this);
one.addActionListener(this);
two.addActionListener(this);
three.addActionListener(this);
plus.addActionListener(this);
dive.addActionListener(this);
four.addActionListener(this);
five.addActionListener(this);
six.addActionListener(this);
multiply.addActionListener(this);
subtract.addActionListener(this);
seven.addActionListener(this);
eight.addActionListener(this);
nine.addActionListener(this);
sin.addActionListener(this);
cos.addActionListener(this);
tan.addActionListener(this);
pie.addActionListener(this);
E.addActionListener(this);
abs.addActionListener(this);
X2.addActionListener(this);
X3.addActionListener(this);
log.addActionListener(this);
sqrt.addActionListener(this);
zero.addActionListener(this);
dot.addActionListener(this);
round.addActionListener(this);
txtfield1.setEnabled(false);
}

public void actionPerformed(ActionEvent e)


{
if(e.getSource()==one){
txtfield1.setText(one.getActionCommand());
}
else if(e.getSource()==two){
txtfield1.setText(two.getActionCommand());
}
else if(e.getSource()==two){
txtfield1.setText(two.getActionCommand());
}
else if(e.getSource()==three){
txtfield1.setText(three.getActionCommand());
}
else if(e.getSource()==four){
txtfield1.setText(four.getActionCommand());
}
else if(e.getSource()==five){
txtfield1.setText(five.getActionCommand());
}
else if(e.getSource()==six){
txtfield1.setText(six.getActionCommand());
}
else if(e.getSource()==seven){
txtfield1.setText(seven.getActionCommand());
}
else if(e.getSource()==eight){
txtfield1.setText(eight.getActionCommand());
}
else if(e.getSource()==nine){
txtfield1.setText(nine.getActionCommand());
}
else if(e.getSource()==plus){
txtfield1.setText(plus.getActionCommand());
}
else if(e.getSource()==subtract){
txtfield1.setText(subtract.getActionCommand());
}
else if(e.getSource()==multiply){
txtfield1.setText(multiply.getActionCommand());
}
else if(e.getSource()==dive){
txtfield1.setText(dive.getActionCommand());
}
}
}
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);
}
}

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.

HTML Scientific Calculator


<!DOCTYPE html>
<html>
<head>
<title>
Scientific Calculator using HTML, CSS and Js
</title>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/mathjs/10.6.4/math.js "
integrity=
"sha512-
BbVEDjbqdN3Eow8+empLMrJlxXRj5nEitiCAK5A1pUr66+jLVejo3PmjIaucRnjlB0P9R3rBUs3g
5jXc8ti+fQ=="
crossorigin="anonymous"
referrerpolicy="no-referrer">
</script>
</head>

<body>
<h1 style="color: green; text-align: center;">
Scientific Calculator</h1>
<form>
<table>
<tr>
<td colspan="6">
<input id="display" type="text">
</td>
</tr>
<tr>
<td><input type="button" value="1"
onclick="display.value += '1'"></td>
<td><input type="button" value="2"
onclick="display.value += '2'"></td>
<td><input type="button" value="3"
onclick="display.value += '3'"></td>
<td><input type="button" value="C"
onclick="display.value = ''"></td>
<td><input type="button" value="⌫"
onclick="backspace()"></td>
<td><input type="button" value="="
onclick="calculate()"></td>
</tr>
<tr>
<td><input type="button" value="4"
onclick="display.value += '4'"></td>
<td><input type="button" value="5"
onclick="display.value += '5'"></td>
<td><input type="button" value="6"
onclick="display.value += '6'"></td>
<td><input type="button" value="-"
onclick="display.value += '-'"></td>
<td><input type="button" value="%"
onclick="display.value += '%'"></td>
<td><input type="button" value="cos("
onclick="display.value += 'cos('"></td>
</tr>
<tr>
<td><input type="button" value="7"
onclick="display.value += '7'"></td>
<td><input type="button" value="8"
onclick="display.value += '8'"></td>
<td><input type="button" value="9"
onclick="display.value += '9'"></td>
<td><input type="button" value="x"
onclick="display.value += '*'"></td>
<td><input type="button" value="!"
onclick="display.value += '!'"></td>
<td><input type="button" value="sin("
onclick="display.value += 'sin('"></td>
</tr>
<tr>
<td><input type="button" value="."
onclick="display.value += '.'"></td>
<td><input type="button" value="0"
onclick="display.value += '0'"></td>
<td><input type="button" value=","
onclick="display.value += ','"></td>
<td><input type="button" value="+"
onclick="display.value += '+'"></td>
<td><input type="button" value="/"
onclick="display.value += '/'"></td>
<td><input type="button" value="tan("
onclick="display.value += 'tan('"></td>
</tr>
<tr>
<td><input type="button" value="E"
onclick="e()"></td>
<td><input type="button" value="pi"
onclick="pi()"></td>
<td><input type="button" value="^"
onclick="power()"></td>
<td><input type="button" value="("
onclick="display.value += '('"></td>
<td><input type="button" value=")"
onclick="display.value += ')'"></td>
<td><input type="button" value="log("
onclick="base10Log()"></td>
</tr>
<tr>
<td><input type="button" value="sqrt("
onclick="squareRoot()"></td>
<td><input type="button" value="ln2"
onclick="display.value += Math.LN2"></td>
<td><input type="button" value="log10("
onclick="base10Log()"></td>
<td><input type="button" value="l2e"
onclick="display.value += Math.LOG2E"></td>
<td><input type="button" value="l10e"
onclick="display.value += Math.LOG10E"></td>
<td><input type="button" value="exp("
onclick="display.value += 'exp('"></td>
</tr>
</table>
</form>
</body>
</html>
CSS
table {
border: 1px solid black;
margin-left: auto;
margin-right: auto;
}

input[type="button"] {
width: 100%;
padding: 20px 40px;
background-color: green;
color: white;
font-size: 24px;
font-weight: bold;
border: none;
border-radius: 5px;
}

input[type="text"] {
padding: 20px 240px;
font-size: 24px;
font-weight: bold;
border: none;
border-radius: 5px;
border: 2px solid black;
text-align: left;
}

display {
text-align: left;
}

Javascript

function backspace() {
let display = document.getElementById("display");
display.value = display.value.slice(0, -1);
}

function calculate() {
let display = document.getElementById("display");
let expression = display.value;
let result;

try {
// Convert trigonometric function inputs from degrees to radians
expression = expression.replace(/sin\(/g, 'sin(' + Math.PI / 180 +
'*');
expression = expression.replace(/cos\(/g, 'cos(' + Math.PI / 180 +
'*');
expression = expression.replace(/tan\(/g, 'tan(' + Math.PI / 180 +
'*');

result = math.evaluate(expression);
display.value = result;
} catch (error) {
display.value = "Error";
}
}

function squareRoot() {
let display = document.getElementById("display");
display.value += "sqrt(";
}

function base10Log() {
let display = document.getElementById("display");
display.value += "log(";
}
function pi() {
let display = document.getElementById("display");
display.value += "pi";
}

function e() {
let display = document.getElementById("display");
display.value += "e";
}

function power() {
let display = document.getElementById("display");
display.value += "^(";
}

You might also like