Sushi

Download as pdf or txt
Download as pdf or txt
You are on page 1of 28

VISVESVARAYA TECHNOLOGICAL UNIVERSITY BELGAUM -590014

Applications of Java Programming (BAI306)

Report On

“Calculator For Prefix And Suffix Expressions”

A Mini-project report submitted in partial fulfillment of the requirements for the award of
the degree of Bachelor of Engineering in Artifical Intelligence and Machine Learning
of Visvesvaraya Technological University, Belgaum.

Submitted by:

Shashwat Yadav (1DT23AI051)


Aviral Sahu (1DT23AI011)
Akshobhya (1DT23AI006)
Nithin (1DT23AI038)

Under the Guidance of:


Miss Shamia Aftab
Assistant Professor, Dept of AIML

DAYANANDA SAGAR ACADEMY OF TECHNOLOGY & MANAGEMENT


Opp. Art of Living, Udayapura, Kanakapura Road, Bangalore- 560082(Affiliated to Visvesvaraya
Technological University, Belagavi and Approved by AICTE, NewDelhi). (Accredited by NBA until
30-06-2025, NAAC (A+))
DAYANANDA SAGAR ACADEMY OF TECHNOLOGY & MANAGEMENT
Opp. Art of Living, Udayapura, Kanakapura Road, Bangalore- 560082
(Affiliated to Visvesvaraya Technological University, Belagavi and Approved by AICTE, NewDelhi).
(Accredited by NBA until 30-06-2025, NAAC (A+))

DEPARTMENT OF ARTIFICAL INTELLIGENCE AND MACHINE


LEARNING

CERTIFICATE
This is to certify that the Mini-Project on Calculator For Prefix And Suffix
Expressions”has been successfully carried out by ShashwatYadav(1DT23AI051)
,Akshobhyaks(1DT23AI006) ,Nithin(1DT23AI038) ,Aviral (1DT23AI011),a Bonafide
students of Dayananda Sagar Academy of Technology and Management in partial
fulfilment of the requirements for the award of degree in Bachelor of Engineering in
Artificial Intelligence and Machine Learning of the Visvesvaraya Technological
University, Belgaum during academic year 2024. It is certified that all
corrections/suggestions indicated for Internal Assessment have been incorporated in the
report deposited in the departmental library.

Signature Signature

Miss Shamia Aftab Dr. Sandhya N


Assistant Professor, Professor & HoD,
Dept of AIML,DSATM. Dept of AIML,DSATM.
ACKNOWLEDGEMENT

It gives us immense pleasure to present before you our project titled “Calculator For

Prefix And Suffix Expressions” The joy and satisfaction that go with the successful

completion of any task would be incomplete without the mention of those who made it

possible. We are glad to express our gratitude towards our prestigious institution

DAYANANDA SAGAR ACADEMY OF TECHNOLOGY AND MANAGEMENT for

providing us with utmost knowledge, encouragement, and the maximum facilities in

undertaking this project.

We sincerely acknowledge the guidance and constant encouragement of our mini- project

guide Assistant professor Miss Shamia Aftab, Asst. Professor, Dept of AIML .

We express our deepest gratitude and special thanks to Dr. Sandhya N, Prof &H.O.D,

Dept.Of Artificial Intelligence and Machine Learning, for all her guidance and

encouragement.

We wish to express a sincere thanks to our respected principal

Dr.M. Ravishankar, Principal, DSATM for all their support .

TEAM MEMBERS NAME (USN)

Shashwat Yadav (1DT23AI051)


Aviral Sahu (1DT23AI011)
Akshobhya (1DT23AI006)
Nithin (1DT23AI038
ABSTRACT
The project, "Expression Evaluator," is an advanced Java-based graphical user interface
(GUI) application designed to facilitate the evaluation of mathematical expressions in
infix, postfix, and prefix formats. This versatile tool enhances the comprehension and
computation of diverse expression types, which are foundational in mathematics,
computer science, and related fields.

By utilizing stack-based algorithms, the application ensures precise and efficient parsing
and computation of expressions, providing a reliable solution for complex calculations.
Users interact with the application through an intuitive interface that allows seamless
input of expressions, selection of the preferred evaluation mode, and instant retrieval of
accurate results. The design emphasizes usability, integrating a visually clean layout with
robust error-handling mechanisms to prevent and address user errors effectively.

The project exemplifies the synergy between data structures and algorithms, showcasing
their application in real-world problem-solving scenarios. Leveraging Java's Swing
library, it delivers a dynamic and interactive desktop application that not only serves as a
practical computational tool but also as an educational resource for learning about
expression evaluation and stack-based processing. This project underscores the potential
of combining algorithmic concepts with Java's rich GUI capabilities to develop functional
and user-friendly software solutions.
TABLE OF CONTENTS

CHAPTER CHAPTER NAME PAGE

1 INTRODUCTION 1

1.1 Background 1

1.2 Problem Definition 1

1.3 Motivation 2

1.4 Objectives 2

1.5 Scope of the project 3

2 REQUIREMENTS 4

2.1 Hardware Requirements 4

2.2 Software Requirements 4

3 Design 5

3.2 Flowchart 11
4 IMPLEMENTATION 10

4.1 Modules and their 10


Description

4.2 Algorithm 11

4.3 SOURCE CODE 12

4.3.1 Frontend /Backend 12


Connection

5 TESTING 17

6 RESULT ANALYSIS AND 19


SCREEN SHOTS

7 CONCLUSION AND 27
FUTURE WORK

7.1 Conclusion 27

7.2 Advantages 27

7.3 Future Enhancement 27

8 BIBLIOGRAPHY 28

8.1 Book References 28

8.2 Website References 28


CHAPTER 1

INTRODUCTION
1. Background

Mathematical expressions in infix, postfix, and prefix formats are fundamental in fields
like mathematics, computer science, and programming. These formats are integral to
problem-solving, compiler design, and algorithm development. While infix is the most
commonly used form in arithmetic calculations, postfix and prefix are pivotal in stack-
based computations and systems where operator precedence must be explicitly handled.

Manually evaluating such expressions can be prone to human error and time-consuming,
especially for complex expressions. The need for a reliable and user-friendly tool to
evaluate these expressions efficiently has become increasingly significant in educational
and computational contexts.

This project addresses the challenge by developing an intuitive Java-based Expression


Evaluator. The system automates the evaluation of infix, postfix, and prefix expressions,
providing accurate and instant results through a GUI interface. By employing stack-based
algorithms, it simplifies the process, offering a seamless user experience for learners and
professionals alike.

2. Problem Definition

The problem addressed by this project is the absence of an efficient and user-friendly
system for evaluating mathematical expressions in infix, postfix, and prefix formats.
Currently, the manual calculation of such expressions is prone to errors, requires
significant effort, and demands a deep understanding of operator precedence and
associativity rules.

This project targets several challenges associated with expression evaluation, including:

 Handling the complexity of different expression formats effectively.

 Ensuring accuracy in computations while adhering to the rules of operator


precedence and associativity.
 Providing an intuitive and accessible interface for users unfamiliar with
programming or algorithmic techniques.

 Minimizing errors caused by manual input or incorrect parsing of expressions.

By addressing these challenges, this project aims to simplify the process of mathematical
expression evaluation, making it accessible and reliable for both students and
professionals.

3. Motivation

Manual System: Existing methods for evaluating mathematical expressions are often
manual and highly time-consuming. These approaches are prone to human error,
especially when dealing with complex expressions involving multiple operators and
parentheses.

Technical System: With advancements in technology, there is a pressing need to adopt


systems that are fast, accurate, user-friendly, and reliable. Leveraging stack-based
algorithms and graphical interfaces, this project aims to modernize the evaluation process,
providing users with a seamless and efficient tool for handling infix, postfix, and prefix
expressions.

4.Objective
The primary objective of this project is to develop a Java-based application for
evaluating mathematical expressions in infix, postfix, and prefix formats using a
graphical user interface (GUI). The system is designed to provide accurate, efficient, and
user-friendly evaluation of expressions to simplify the computational process.

The specific objectives of the project are:

1. To develop a user-friendly GUI that allows users to input expressions and


choose the evaluation mode (infix, postfix, or prefix).

2. To implement a robust postfix evaluation module using stack-based algorithms


for accurate and efficient computation.

3. To design a prefix evaluation module capable of handling complex operator


precedence and associativity rules.
4. To develop an infix evaluation module that incorporates parentheses and
operator precedence using stacks.

5. To ensure real-time error handling for invalid or incomplete expressions,


improving user experience and reliability.

6. To create a scalable and modular codebase for future enhancements, such as


support for additional functionalities or expression formats.

7. To provide a comprehensive, interactive tool for educational and practical


applications in mathematics and computer science.

5. Scope of the project

The primary objective of the Expression Evaluator project is to automate and simplify the
process of evaluating mathematical expressions in infix, postfix, and prefix formats. This
Java-based GUI application is designed to handle various scenarios encountered in
expression evaluation while providing an intuitive interface for users.

The project scope includes:

 Expression Evaluation: Supporting the evaluation of infix, postfix, and prefix


expressions using stack-based algorithms for accuracy and efficiency.

 User Interface: Developing an intuitive graphical interface that allows users to


input expressions and select the desired evaluation mode.

 Error Handling: Ensuring robust handling of invalid or incomplete expressions,


providing clear feedback to the user.

 Educational Utility: Serving as a tool for learning and understanding different


expression formats and their computational processes.

 Practical Applications: Offering a reliable resource for students, educators, and


professionals in mathematics and computer science.

 Scalability: Building a modular framework that can be extended to include


additional features or support other expression formats in the future.
CHAPTER 2
REQUIREMENTS

The requirements for the Expression Evaluator project can be categorized into hardware
and software requirements. The hardware requirements specify the minimum system
configuration needed to run the application, while the software requirements outline the
essential tools and technologies required to build and execute the project.

2.1 Hardware Requirements


The hardware requirements for the project are minimal, making it compatible with
most modern systems.
 Processor: Intel Core i3 or AMD Ryzen 3 or higher
 Processor Speed: 1 GHz or above
 Hard Disk: 10 GB free space
 RAM: 4 GB or above
 Display: 1024x768 resolution or higher

2.2 Software Requirements


Programming Language: Java
IDE Used: IntelliJ IDEA, Eclipse, or NetBeans
User Interface Design: Java Swing
Libraries Used: Java AWT and Swing for GUI development
Operating System: Windows, macOS, or Linux with Java Runtime
Environment (JRE) 8 or above installed
Other Tools: JDK 8 or above for compilation and execution
CHAPTER 3
DATABASE DESIGN

FLOWCHART
CHAPTER 4

IMPLEMENTATION

The implementation chapter describes the design, structure, and components involved in
building the Simple Calculator project in Java. This chapter outlines the different
modules and their functionality, focusing on the core aspects of the program, from user
interaction to the logic behind the calculator.Admin Module

4.1 Modules and their Description

 The Simple Calculator project consists of the following key modules:


 User Module: This module handles user input, displays the result, and provides an
interface for interaction with the calculator.
 Admin Module: Though the Simple Calculator does not require an Admin interface
in its basic form, for complex scenarios (e.g., extended functionalities like saving
history), an admin module could be added in future updates.
 Below are the detailed descriptions of these modules:
 User Module
 The User Module is responsible for providing the main functionality of the calculator,
which includes basic arithmetic operations such as addition, subtraction,
multiplication, and division.
 Key Functions of User Module:
 Start Page: The user is welcomed with the calculator’s user interface, where they can
start entering values.
 Input Fields: The user can enter numbers and operators.
 Operations: The system supports basic mathematical operations, including:
 Addition (+)
 Subtraction (-)
 Multiplication (*)
 Division (/)
 Display: After performing an operation, the result is displayed on the screen.
 Clear/Reset: Users can clear the current calculation and reset the input fields.
 Admin Module
 In this specific version of the project, the admin module might not be directly
involved since the core function is a simple calculator. However, in an extended
version, this module would allow:
 History Tracking: Saving a record of past calculations.
 User Management: If the project expands to multi-user functionalities, admins would
be able to manage users and their data.

4.2 ALGORITHM

Step 1: Display the calculator interface.


Step 2: User inputs the first number.
Step 3: User selects an operator (+, -, *, /).
Step 4: User inputs the second number.
Step 5: When "=" is clicked, perform the operation.
Step 6: Display the result.
Step 7: If "C" is clicked, clear the input and reset.
Step 8: Repeat steps 2-7 as needed.
4.3 SOURCE CODE
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.Stack;
import javax.swing.*;

public class h {
public static void main(String[] args) {
JFrame frame = new JFrame("Expression Evaluator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 400);

JTextField inputField = new JTextField();


JTextArea outputArea = new JTextArea();
outputArea.setEditable(false);
JButton evaluateButton = new JButton("Evaluate");
JComboBox<String> modeSelector = new JComboBox<>(new String[]{"Postfix",
"Prefix", "Infix"});

evaluateButton.addActionListener((ActionEvent e) -> {
String expression = inputField.getText().trim();
String mode = (String) modeSelector.getSelectedItem();

if (expression.isEmpty()) {
outputArea.setText("Please enter an expression.");
return;
}

try {
double result = switch (mode) {
case "Postfix" -> evaluatePostfix(expression);
case "Prefix" -> evaluatePrefix(expression);
case "Infix" -> evaluateInfix(expression);
default -> 0;
};
outputArea.setText("Result: " + result);
} catch (Exception ex) {
outputArea.setText("Error: Invalid Expression");
}
});

frame.setLayout(new GridLayout(5, 1));


frame.add(new JLabel("Enter Expression:"));
frame.add(inputField);
frame.add(modeSelector);
frame.add(evaluateButton);
frame.add(new JScrollPane(outputArea));

frame.setVisible(true);
}

private static double evaluatePostfix(String expr) {


Stack<Double> stack = new Stack<>();
String[] tokens = expr.split(" ");
for (String token : tokens) {
if (isNumber(token)) {
stack.push(Double.parseDouble(token));
} else {
double b = stack.pop();
double a = stack.pop();
stack.push(applyOp(token.charAt(0), a, b));
}
}
return stack.pop();
}

private static double evaluatePrefix(String expr) {


Stack<Double> stack = new Stack<>();
String[] tokens = expr.split(" ");
for (int i = tokens.length - 1; i >= 0; i--) {
String token = tokens[i];
if (isNumber(token)) {
stack.push(Double.parseDouble(token));
} else {
double a = stack.pop();
double b = stack.pop();
stack.push(applyOp(token.charAt(0), a, b));
}
}
return stack.pop();
}

private static double evaluateInfix(String expr) {


Stack<Double> values = new Stack<>();
Stack<Character> ops = new Stack<>();
for (int i = 0; i < expr.length(); i++) {
char c = expr.charAt(i);
if (Character.isWhitespace(c)) continue;

if (Character.isDigit(c) || c == '.') {
StringBuilder sb = new StringBuilder();
while (i < expr.length() && (Character.isDigit(expr.charAt(i)) || expr.charAt(i)
== '.')) {
sb.append(expr.charAt(i++));
}
i--; // Step back one character to avoid skipping the last digit
values.push(Double.parseDouble(sb.toString()));
} else if (c == '(') {
ops.push(c);
} else if (c == ')') {
while (ops.peek() != '(') {
values.push(applyOp(ops.pop(), values.pop(), values.pop()));
}
ops.pop(); // Remove '(' from stack
} else if ("+-*/^".indexOf(c) != -1) {
while (!ops.isEmpty() && precedence(ops.peek()) >= precedence(c)) {
values.push(applyOp(ops.pop(), values.pop(), values.pop()));
}
ops.push(c);
}
}
while (!ops.isEmpty()) {
values.push(applyOp(ops.pop(), values.pop(), values.pop()));
}
return values.pop();
}

private static double applyOp(char op, double a, double b) {


return switch (op) {
case '+' -> a + b;
case '-' -> a - b;
case '*' -> a * b;
case '/' -> {
if (b == 0) throw new ArithmeticException("Division by zero");
yield a / b;
}
case '^' -> Math.pow(a, b);
default -> 0;
};
}

private static int precedence(char op) {


if (op == '+' || op == '-') return 1;
if (op == '*' || op == '/') return 2;
if (op == '^') return 3;
return 0;
}

private static boolean isNumber(String str) {


try {
Double.parseDouble(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
CHAPTER 5

TESTING

5.1 Objective of Testing


The objective of testing is to ensure that the application is functioning as
intended, with no bugs, errors, or issues. Testing verifies that the front-end
interface, back-end logic, and database interactions are working properly and
efficiently. It ensures that the system meets the requirements specified in the
design phase and provides a smooth user experience.

5.2 Testing Methodology


The following testing methodologies were used during the development of
the project:

 Unit Testing: Individual functions or units of code are tested to


ensure they work correctly.

 Integration Testing: Ensures that different modules or components of


the application work well together.

 System Testing: Full system testing to check if all components work


together as a complete solution.

 User Acceptance Testing (UAT): Performed by the end-users to


verify if the system meets their expectations.

5.3 Types of Testing

 Functional Testing: This type of testing focuses on verifying the


functionality of the calculator system, ensuring the input and output
functions work as expected (e.g., addition, subtraction, multiplication,
division).
 Regression Testing: After each update or change, regression testing
ensures that previously working features still function correctly.

 Usability Testing: Ensures that the user interface (UI) is user-friendly


and intuitive. Testing was done to ensure that the calculator's layout
and design are simple to navigate.

5.4 Test Cases

 Input: 3 + 5 * (2 - 8) / 2 (Infix)
Expected Output: -12
Result: Pass
 Input: 2 3 + 4 * (Postfix)
Expected Output: 20
Result: Pass
 Input: + 2 * 3 - 4 5 (Prefix)
Expected Output: 1
Result: Pass
 Input: ((8 / 4) + (3 ^ 2)) * 2 (Infix)
Expected Output: 22
Result: Pass
 Input: 6 3 - 2 + * (Postfix)
Expected Output: Error message "Invalid expression"
Result: Pass
 Input: - 10 / 15 (Prefix)
Expected Output: 1
Result: Pass
 Input: (2 + 3) * ((4 / 2) (Infix)
Expected Output: Error message "Invalid expression: missing parenthesis"
Result: Pass
 Input: 5 2 3 * + (Postfix)
Expected Output: 11
Result: Pass
 Input: * + 5 6 - 7 (Prefix)
Expected Output: Error message "Invalid expression: missing operand"
Result: Pass
 Input: (10 + (2 * 3)) / 0 (Infix)
Expected Output: Error message "Cannot divide by zero"
Result: Pass

5.5 Bug Fixes


During testing, a few bugs were discovered and fixed:

 Bug 1: The division operation was not handling division by zero


properly. It was fixed by adding a condition to display an error
message.

 Bug 2: The clear button was not resetting the display properly. This
was fixed by modifying the event listener for the "C" button.

5.6 Conclusion of Testing


After thorough testing, the application was found to meet the required
functionality. All core operations of the calculator (addition, subtraction,
multiplication, division) worked as expected, and the error-handling
mechanisms (such as division by zero) were implemented correctly. The user
interface was also easy to use, and no critical bugs were found during the
testing phase. The application is now ready for deployment .
CHAPTER 6

RESULT ANALYSIS AND SCREENSHOTS

1. Accuracy:

o The system successfully evaluates mathematical expressions in


Prefix, Postfix, and Infix formats with accurate results.

2. Error Handling:

o Invalid expressions, division by zero, and mismatched


parentheses are correctly identified, displaying appropriate error
messages.

3. User Interface:

o The GUI is intuitive and allows users to enter expressions,


choose evaluation modes, and view results seamlessly.

4. Performance:

o The program handles both simple and complex expressions


efficiently without delays.

5. Testing Outcome:

o All predefined test cases, including edge cases like nested


parentheses and invalid inputs, have passed successfully.

6. Key Achievements:

o Robust handling of operator precedence and exponentiation.

o Modular design ensures scalability and easy maintenance.


SCREENSHOTS
CHAPTER 7 CONCLUSION AND FUTURE WORK

7.1 CONCLUSION
The Simple Calculator project serves as an efficient, reliable, and easy-to-use tool for
basic arithmetic calculations. It automates the process of performing addition, subtraction,
multiplication, and division, reducing the chances of human error. The project was
designed to be simple and intuitive, ensuring that users can quickly learn how to use it.
The system was tested rigorously and confirmed to be functional, with appropriate error
handling for edge cases such as division by zero. This project has met its objectives,
providing a fast, user-friendly calculator that performs essential operations seamlessly.

7.2 ADVANTAGES
The Simple Calculator application has the following advantages:
♦ Fast: The calculator performs calculations instantaneously, with minimal delay.
♦ Efficient: All arithmetic operations are carried out accurately and quickly, ensuring
reliable results.
♦ Reliable: With thorough testing, the calculator proves to be dependable in all tested
scenarios.
♦ Avoids Human Error: The calculator eliminates manual computation errors, providing
accurate results.
♦ User-friendly: The simple interface makes it easy for users of all technical
backgrounds to use.
♦ Error Handling: The application effectively handles division by zero and other invalid
operations.
♦ Accessibility: The application can be easily extended with additional features such as
scientific operations if needed in the future.

7.3 FUTURE ENHANCEMENT


While the current Simple Calculator serves its primary purpose well, there are
opportunities for future enhancements:

 Scientific Calculator: The application can be expanded to support advanced


mathematical operations such as square roots, trigonometric functions, logarithms,
etc.
 Memory Functions: Implement features like storing previous results in memory
for later use.
 User Interface Improvements: Enhance the UI to include additional themes or a
more modern design, making it visually appealing and customizable.
 Multi-platform Support: The calculator can be extended to mobile platforms
(iOS, Android) to cater to a larger audience.
 Localization: Add multiple language support to make the calculator accessible to
users globally.

With these enhancements, the Simple Calculator can become a more comprehensive tool
for users in various fields, from education to engineering, providing a reliable and
efficient solution for all types of calculations.
CHAPTER 8

BIBLIOGRAPHY

8.1 BOOK REFERENCES


Learn to Code HTML and CSS: Develop and Style Websites (Web Design Courses),
Kindle Edition by Shay Howe
The Joy of PHP Programming: A Beginner’s Guide by Alan Forbes

8.2 WEBSITE REFERENCES


W3Schools - What is Web Development
GeeksforGeeks - HTML Tutorial
TutorialsPoint - PHP Tutorial
YouTube - PHP Tutorial for Beginners

KillerPHP - PHP Learning Resources


PERSONAL DETAILS
NAME: SHASHWAT YADAV

USN: 1DT20AI051

SEMESTER: 3rd SEM

COLLEGE: DAYANANDA SAGAR ACADEMY OF TECHNOLOGY AND


MANAGEMENT

EMAIL-ID: 1dt23ai051@dsatm.edu.in

PHONE NO: 6393355490

NAME: AVIRAL SAHU

USN: IDT20AI011

SEMESTER: 3rd SEM

COLLEGE: DAYANANDA SAGAR ACADEMY OF TECHNOLOGY AND


MANAGEMENT

EMAIL-ID: 1dt23ai011@dsatm.edu.in

PHONE NO: 6263555973

NAME: Akshobhya

USN: IDT20AI006

SEMESTER: 3rd SEM

COLLEGE: DAYANANDA SAGAR ACADEMY OF TECHNOLOGY AND


MANAGEMENT

EMAIL-ID: 1dt23ai006@dsatm.edu.in

PHONE NO: 7349422500


NAME: NITHIN

USN: IDT20AI038

SEMESTER: 3rd SEM

COLLEGE: DAYANANDA SAGAR ACADEMY OF TECHNOLOGY AND


MANAGEMENT

EMAIL-ID: 1dt23ai038@dsatm.edu.in

PHONE NO: 7975622848

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy