0% found this document useful (0 votes)
17 views77 pages

Program 1

This document outlines the development process of an application for the Skin Beauty Aesthetic Centre, focusing on automating client authentication, treatment cost calculation, and discount application. It details the algorithm design using pseudocode, the steps to build the application in Java with a GUI, and the conversion of the algorithm into functional code. Additionally, it addresses challenges faced during development, coding standards applied, and enhancements made using an IDE.

Uploaded by

thazinminlwin90
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views77 pages

Program 1

This document outlines the development process of an application for the Skin Beauty Aesthetic Centre, focusing on automating client authentication, treatment cost calculation, and discount application. It details the algorithm design using pseudocode, the steps to build the application in Java with a GUI, and the conversion of the algorithm into functional code. Additionally, it addresses challenges faced during development, coding standards applied, and enhancements made using an IDE.

Uploaded by

thazinminlwin90
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1.

Algorithm Definition Using a Design Tool (Pseudocode)


To begin the development of the program, I designed the algorithm using pseudocode. This
approach helped to clearly define the logical flow of operations, user input requirements, and
processing rules before writing any code.

plaintext
CopyEdit
START

DEFINE correct_password = "admin123"


SET attempts = 0

WHILE attempts < 3


PROMPT user to enter password
IF password == correct_password THEN
PRINT "Access Granted"
BREAK
ELSE
INCREMENT attempts
PRINT "Incorrect Password"
IF attempts == 3 THEN
PRINT "Access Denied"
END

INPUT client ID, name, membership duration


DISPLAY list of available treatments and prices
INPUT number of selected treatments

SET total_cost = 0
FOR each treatment
INPUT treatment name and quantity
RETRIEVE price from treatment list
CALCULATE cost = price * quantity
ADD cost to total_cost
STORE treatment details

IF total_cost > 1500 THEN discount = 0.15


ELSE IF total_cost > 1000 THEN discount = 0.10
ELSE IF total_cost > 500 THEN discount = 0.05
ELSE discount = 0.00

IF membership_months >= 12 THEN ADD 0.05 to discount

CALCULATE discount_amount = total_cost * discount


CALCULATE final_cost = total_cost - discount_amount

DISPLAY client name


DISPLAY itemised list of treatments and costs
DISPLAY total_cost, discount_amount, final_cost

END
2. Steps Required to Build the Application
To develop a working application based on the algorithm, the following steps were followed:

Step 1: Requirement Analysis

 Understand the purpose of the application: user authentication, treatment selection,


discount calculation, and invoice generation.
 Define expected inputs (e.g. password, client data, treatment info) and outputs (formatted
invoice).

Step 2: Design Algorithm

 Use pseudocode (see Section 1) to break the logic into clear, sequential steps.
 Identify decision points such as discount eligibility and authentication validation.

Step 3: Choose Development Tools

 Select a suitable programming language and development environment.

Step 4: Set Up IDE

 Configure a new project in PyCharm.


 Install Python 3.10 interpreter.
 Organize project files (main.py, resources, test files).

Step 5: Develop and Test Modules

 Authentication module
 Treatment selection and input module
 Discount application logic
 Invoice output formatting

Step 6: Debug, Optimize, and Document

 Use IDE tools (debugger, profiler) to find and resolve issues.


 Apply code standards for readability and maintainability.
 Comment and annotate the final source code.

3. Converting the Algorithm into a Working Program


Programming Language Used: Python

Why Python?

 Clear syntax for beginners and professionals


 Support for essential structures (lists, dictionaries)
 Accurate floating-point arithmetic
 Strong IDE support for debugging and optimization
 Rapid development for console-based applications

Conversion Process

Algorithm Step Code Translation


WHILE attempts < 3 Implemented as a while loop with counter
IF password == correct_password Direct if condition with equality check
INPUT steps Python input() functions with try-except
Treatment storage List of dictionaries to hold name, qty, cost
Discount tiers if-elif structures and logic operations
Output formatting f"£{value:.2f}" for two-decimal precision

Additional enhancements included:

 Validating all user inputs


 Displaying menu-like treatment options
 Adding function-based modular code structure (def get_treatments())

4. Relationship Between Algorithm and Program Code


The transformation from the pseudocode algorithm to program code was mostly linear, but
practical implementation required some modifications.

Pseudocode Element Code Implementation Changes


Password input Added feedback and input validation using loops
Treatment loop Extended to include treatment validation
Discount logic Applied cap to prevent excessive combined discounts
Input/output operations Refined with clearer prompts and formatted display
Data structures Used dictionaries and lists for efficiency

Parts that Remained the Same

 Overall control flow: input → process → output


 Tier-based and loyalty discount logic
 Loop structure for multiple treatment entries

Parts That Changed

 Input handling improved with exception management


 Real-time validation for treatments from a predefined list
 Better formatting using string templates and line spacing

5. Challenges Faced in Code Conversion


5.1 Input Validation

 Issue: User could enter non-numeric input for quantities or durations.


 Solution: Used try-except blocks and .isdigit() checks to enforce input types.

5.2 Floating-Point Precision

 Issue: Totals like 499.999999 were being shown due to floating-point rounding.
 Solution: Used round() and format(value, ".2f") consistently.

5.3 Data Structure Management

 Issue: Needed to dynamically store treatment names, quantities, and costs.


 Solution: Used list of dict objects, one per treatment.

5.4 Cumulative Discounts

 Issue: Loyalty and tier discounts combined could exceed reasonable limits.
 Solution: Applied min(discount_rate, 0.20) to cap total discount at 20%.

5.5 Code Repetition

 Issue: Redundant code blocks for input/output.


 Solution: Modularized using custom functions for reusability.

6. Coding Standards Used


The following coding standards were applied:
Standard Description
PEP 8 Compliance Followed naming, spacing, and indentation rules
Function Naming Used snake_case for all function and variable names
Commenting and Docstrings Used for each function and key logic block
Variable Naming Clear and meaningful (e.g., total_cost, client_name)
Modularization Divided program into reusable functions
Error Handling All inputs validated to prevent crashes

Tools Used for Standards:

 PyCharm built-in linting


 PEP 8 style checker plugin

These standards ensure that the application is readable, testable, and maintainable by any team
member.

7. Enhancing the Original Algorithm Using IDE Features


7.1 Identifying and Solving Logical Errors

Tools Used:

 PyCharm debugger with line-by-line execution


 Conditional breakpoints for discount application

Example Fix:

 Incorrect calculation: discounts being applied before full cost was added
Resolved By: Reordering calculations after treatment loop

7.2 Debugging Errors in the Program

 Used the variable watch window to track cost totals


 Identified and fixed incorrect variable scoping in loops
 Used print() statements during early development for traceability

7.3 Version Control

 System: Git (via PyCharm)


 Created branches: main (stable), dev (feature testing)
 Sample commit messages:
o fix: resolved incorrect discount calculation
o add: input validation for quantity and treatment name
7.4 Performance Monitoring

 Profiler: Used PyCharm’s performance tool to monitor runtime bottlenecks


 Identified redundant dictionary lookups and optimized by caching treatment prices

7.5 Refinement Using Code Constructs

 Replaced repetitive if conditions with dictionary lookups


 Used functions for repeated logic:
o calculate_total_cost()
o apply_discounts()
o print_invoice()
 Introduced constants for treatment prices to improve maintainability

8. Conclusion
The process of developing a working application from a structured algorithm involved several
phases — from conceptual design to implementation and enhancement. The algorithm served as
a blueprint, and Python enabled rapid translation into functional code.

The use of an IDE (PyCharm) significantly improved the development experience by providing
tools for debugging, version control, and performance monitoring. By adhering to coding
standards and modular design, the resulting application is robust, maintainable, and easy to
extend.

The final program successfully meets the Skin Beauty Aesthetic Centre’s requirements:

 Secure authentication
 Dynamic treatment entry
 Accurate tiered and loyalty-based discount computation
 Clear, formatted invoice output
1. Algorithm Definition with Design Tool (Pseudocode)
I began designing the program by writing the algorithm in pseudocode.
This was to define the logical flow of operations, input requirements of the user,
and processing instructions before coding.
plaintext
CopyEdit
START
DEFINE correct_password = "admin123"

SET attempts = 0
WHILE attempts < 3

PROMPT user to enter password


IF password == correct_password TH
PRINT "Access Granted"
BREAK
ELSE
INCREMENT attempts
1. Introduction
This report details the process of designing an algorithm and subsequently developing a working
application for the Skin Beauty Aesthetic Centre. The application aims to automate client
authentication, calculate treatment costs, and apply tiered and loyalty discounts based on
monthly spending and membership duration. This document will cover the definition of the
algorithms, the steps taken to build the application, the conversion process from algorithm to
code, potential challenges, coding standards employed, and the enhancements made to the
algorithm and program during development using an Integrated Development Environment
(IDE). This updated report focuses on Java as the chosen programming language and the
implementation of a Graphical User Interface (GUI).
1. Introduction
The process of creating an algorithm and then a functional
application for the Skin Beauty Aesthetic Center is described
in this report. Automating client authentication, calculating
treatment costs, and applying tiered and loyalty discounts
based on monthly spending and membership duration are
the goals of the app. The definition of the algorithms, the
stages involved in building the application, the process of
converting the algorithm to code, potential difficulties, the
coding standards used, and the improvements made to the
program and algorithm while it was being developed using
an Integrated Development Environment (IDE) will all be
covered in this document. The chosen programming
language, Java, and the creation of a Graphical User
Interface (GUI) are the main topics of this updated report.

2. Definition of an Algorithm
The two main algorithms at the heart of the Skin Beauty
Aesthetic Centre application are the Treatment Cost
Calculation with Discount Application and User
Authentication. Regardless of the interface or programming
paradigm used, these algorithms always follow the same
logical flow.

2.1. User Authentication Algorithm 1


A maximum of three login attempts are permitted by this
algorithm, which regulates system access.

3. A summary of the actions needed to create the application


Setting up the development environment, testing, and
deployment are some of the crucial steps involved in creating
a Java GUI application.

Recognize Requirements: Evaluate the client's needs in


detail, noting all necessary inputs, procedures, and outputs.

Algorithm Design: Create comprehensive algorithms (such


as flowcharts and pseudocode) for every essential function
(discounting, calculation, and authentication). (Finished in
Section 2).

Select the IDE and programming language (Java): Choose


an IDE like Eclipse or IntelliJ IDEA for development, and
Java because of its strong GUI frameworks and platform
independence.
Create GUI Layout: Draw the user interface, noting the
components that are required (buttons, text fields, labels,
lists, and tables for treatments).

Establish Project Structure: Build a Java project that is


well-structured and contains the right packages for each of
the various issues (e.g., ui, logic, model).

Create the main window (JFrame), panels (JPanel), input


fields (JTextField, JPasswordField), buttons (JButton), and
display areas (JTextArea, JLabel) by writing Java code
using Swing.

Put event handling into practice by adding ActionListener to


buttons and other interactive components so they can react
to user input. For programming that is event-driven, this is
essential.

Implement User Authentication Logic: Write code that


integrates GUI input (JPasswordField) and output
(JLabel/JOptionPane for messages) with password
authentication logic, including tracking attempts and
lockout.
Put Data Input Logic (GUI) into Practice: Get client ID,
name, selected treatments (from checkboxes or a table, for
example), number of sessions, and membership duration
data from GUI components. Text from JTextFields will need
to be parsed for this

To improve the separation of concerns, implement Core


Calculation Logic by creating Java classes and methods that
compute the total cost of treatments based on the prices of
selected services. These methods should be separated from
the GUI.

Put Discount Logic into Practice: Write the conditional logic


that applies loyalty and spending-tiered discounts as
methods inside the calculation logic.

Update GUI with Output: Enter the itemized list, total costs,
discount amounts, and final cost into GUI elements (such as
JTextArea or JLabels).

Java Exceptions Error Handling: Use try-catch blocks to


display intelligible error messages in dialogs (JOptionPane)
and gracefully handle invalid inputs (e.g.,
NumberFormatException when parsing non-numeric text).
Testing: Run integration tests for the complete GUI
application flow and unit tests for each logic class separately.

Debugging: Find and address any logical errors using the


IDE's features.

Refinement and Optimization: Enhance the user experience,


readability, and efficiency of the code (e.g., responsive
layout, clear input validation feedback).

Documentation and Comments: Include inline comments for


complex logic and Javadoc comments for classes and
methods.

Version Control: To manage various code versions and keep


track of changes, use an IDE's built-in version control
system (such as Git).

4. Creating a Functional Program from the Algorithm


4.1. Selecting an Appropriate Programming Language
Java has been selected as the programming language for this
application, with its Swing library being used for the
graphical user interface.
Motives behind selecting Java (with Swing):

Platform Independence (WORA): If a Java Virtual Machine


(JVM) is installed, Java's "Write Once, Run Anywhere"
rule guarantees that the program can run on a variety of
operating systems without requiring any changes.

Scalability and Robustness


Java's strong typing helps detect errors during compilation,
resulting in more reliable applications. It works well with
bigger, more intricate systems.

Object-Oriented Paradigm
Java's intrinsic object-orientedness makes it a good choice
for creating modular and maintainable graphical user
interfaces.

Rich Ecosystem and Libraries


The Swing framework, which is part of Java's extensive
ecosystem, is used to create robust desktop graphical user
interfaces.
Powerful IDEs (such as IntelliJ IDEA, Eclipse, and
NetBeans) that provide outstanding features for GUI design,
debugging, refactoring, and project management are a
major asset to Java development.
Swing comes with built-in support for event-driven
programming, which is crucial for interactive graphical user
interfaces (GUIs) where user events (button clicks, text
input) initiate actions.

4.2. Outlining the Conversion Process


Every logical step and construct is translated into its
corresponding Java syntax during the pseudocode to Java
code conversion process, with notable modifications made
for the graphical user interface.

Java is object-oriented in terms of classes and objects. We


will use classes (such as SkinBeautyApp,
AuthenticationPanel, CalculationPanel, and
TreatmentCalculator) in place of just functions. The
application becomes modular as a result.

Operation The main application class or an authentication


class can use AuthenticateUser() as a method.
In a utility class or the main application class, SET
treatmentPrices = {...} turns into a static final Map<String,
Double>.

Variables and Data Types: Java variables with explicit type


declarations (String, int, double, boolean, List<Map<String,
Object>>) are mapped to pseudocode variables.

SET isAuthenticated = FALSE turns into the boolean


isAuthenticated = false;

SET sumCostBeforeDiscount = 0.00 doubles the


sum.CostBeforeDiscount = 0.00

SET itemizedTreatments = [] yields List<Map<String,


Object>> itemizedTreatments = new ArrayList<>(); (a list of
objects/maps in Java).

Structures of Control:

IF-ELSE IF-ELSE conditional statements: Like Python,


these translate directly to Java's if-else if-else blocks.

Loops (WHILE, FOR EACH):


While attempts < maxAttempts AND isAuthenticated is
FALSE, it becomes while (attempts < MAX_ATTEMPTS
&&!isAuthenticated).

In pseudocode, the statement "WHILE TRUE" for


continuous input frequently denotes a continuous GUI input
loop; however, in Java GUI, it indicates that input fields are
always accessible and that button clicks initiate processing.

A Java-enhanced for loop is created for each treatment


entry in selectedTreatmentsData: for (Map<String, Object>
treatmentEntry: selectedTreatmentsData)

JCheckBoxes, JComboBoxes, or filling out a JTable will be


used for user input when choosing treatments; event
handling will be needed to record selections and quantities.
Arithmetic Operations: The standard arithmetic operators
(+, -, *, and /) are all the same.

String formatting: Java's String.format() method,


DecimalFormat from java.text, or NumberFormat for
currency are used to implement the pseudocode's
FORMAT_TO_TWO_DECIMALS and
FORMAT_PERCENTAGE functions.

Error Handling (Exceptions): When Java converts String


input from JTextField to int or double, it handles runtime
exceptions like NumberFormatException using try-catch
blocks rather than merely checking for invalid input.

5. Examination of the Connection Between Program Code


and Algorithms
The program code and the algorithm have a symbiotic
relationship in which the program code is the actual
implementation and the algorithm provides the logical
framework. Although the underlying algorithms for a GUI
application are the same, their data flow and triggering are
essentially different.
5.1. Algorithm Components That Would Stay the Same Core
The logical flow Password authentication follows the same
sequential steps: check, increase attempt, and lock if
maximum attempts are reached. There is no change in the
sequence in which the total cost, discount rates, and their
application are determined.

Conditional Logic for Discounts: The distinct if check for


loyalty membership and the if-else if-else structure for tiered
spending discounts are directly translated.

Mathematical Formulas: TotalCostBeforeDiscount,


spendingDiscountAmount, loyaltyDiscountAmount,
totalDiscountAmount, and totalCostAfterDiscount all have
the same computations.

Data Relationships: Most likely with Java Maps and Lists,


the structure of itemized treatments (name, sessions, cost)
and the relationship between treatment names and prices
are maintained.
5.2. Modifications That Would Need to Be Made (Java &
GUI Adaptations)
The most notable shift is the paradigm shift to an event-
driven model from sequential/procedural input in
pseudocode. Instead of waiting for READ commands, the
program calls certain methods (actionPerformed in an
ActionListener) in response to user actions (button clicks,
text field changes).

Interface of GUI Components:

Data is obtained from JTextField rather than


input().JPasswordField and getText().getPassword(), or
specific JComboBox/JCheckBox items.

Output is sent to JLabel.setText(), JTextArea.append(), or


JOptionPane.showMessageDialog() rather than print().
Separation of Concerns: Proper GUI design requires
keeping the presentation logic (GUI elements, layout) and
business logic (calculations, authentication rules) apart. It is
possible to implement the pseudocode functions as methods
in a Calculator class that is distinct from the JFrame class.

Because Java is statically typed, variable types (such as


String, int, double, boolean, List, and Map) must be
explicitly declared.

Object-Oriented Design: The program will be organized into


several classes, such as AppFrame, AuthPanel,
CalculationPanel, Treatment, and Client.
Java handles exceptions using both checked and unchecked
exceptions. For operations that have the ability to throw
exceptions, such as NumberFormatException when parsing
user-inputted strings to numbers, try-catch blocks are
required.

Use of the Collection Framework: The conceptual "lists"


and "dictionaries" of pseudocode correspond to Java's
ArrayList, HashMap, LinkedHashMap, and other features
found in the java.util package.

Java's layout managers, such as BorderLayout, FlowLayout,


GridLayout, and GridBagLayout, must be used when
designing the visual arrangement of GUI components in
order to guarantee responsiveness and appropriate sizing.

Resource Management: Explicit resource closing through


try-with-resources is a best practice for file I/O or database
connections (not specifically covered in this scope, but they
are common in Java).

Imports: You must import the required Java packages, such


as javax.swing.*, java.awt.*, java.util.*, and java.text.*.
6. Examining Potential Difficulties When the algorithm is
being converted to Java and GUI program code
Compared to a straightforward command-line version,
converting the algorithm to a Java GUI application presents
a number of difficulties:

GUI Design and Adaptability:

The challenge is to arrange elements in an aesthetically


pleasing manner while making sure they work well on
various screen sizes.

Problem: Interfaces with poor layout (e.g., components


overlapping, too small) may become cluttered, unreadable,
or unusable.

The answer is to carefully choose and combine the Swing


layout managers (FlowLayout for basic rows and columns,
BorderLayout for main structure, and GridBagLayout for
complex forms). JPanels can be used to apply various
layouts and group related components.

Complexity of Event Handling:


Managing user interactions (button clicks, text field changes)
and making sure the right logic is triggered present a
challenge.

Problem: If threading is not done carefully, improperly


wired ActionListeners or intricate event chains may result in
bizarre behavior, an unresponsive user interface, or race
conditions (less of a problem for this simple app, but
relevant for advanced GUIs).

Solution: Make sure that tasks are appropriately delegated


to back-end logic methods and implement ActionListener
interfaces for buttons. Related code can be kept together by
using lambda expressions for listeners or inner classes.

Validation and Conversion of Data Types (GUI Input):

Problem: JTextFields only accepts String input. For


computations, it needs to be parsed to int or double.

Problem: If users enter non-numeric text, a


NumberFormatException will occur and, if left unchecked,
will crash the application.
Solution: Enclose Integer in try-catch
(NumberFormatException) blocks.Double or
parseInt().parseDouble(). If input is incorrect, display
understandable error messages (such as
JOptionPane.showMessageDialog). Check for empty inputs
as well.
Keeping Concerns Separate:

Problem: It's simple to combine business logic with GUI


code, which makes it more difficult to read, test, and
maintain.

Problem: "spaghetti code" in which calculation logic is


entangled with user interface updates.

Solution: Put in place a distinct division (for example,


conceptually using the Model-View-Controller pattern).
Make specific classes for AuthenticationService,
CalculationLogic, and a UIFrame class. In order to update
the display, the UI class gathers input, sends it to the logic
classes, and then gets the results.

Thread Safety (this app's minor):


The problem is that Swing GUI updates have to happen on
the Event Dispatch Thread (EDT). On the EDT, lengthy
tasks will cause the user interface to freeze.

Problem: Although not as important for minor


computations, carrying out complex calculations or network
calls directly in an ActionListener would make the user
interface unresponsive.

Solution: To safely update the user interface on the EDT and


execute lengthy tasks in a background thread, use
SwingWorker or other concurrency mechanisms for more
complicated applications. This project does not require it,
but it is a general Java GUI challenge.

7. An explanation of the coding standards used in Java


source code
Code readability, maintainability, and teamwork all depend
on following coding standards. The following coding
guidelines, which are mostly derived from Oracle's Java
Code Conventions, have been used for this Java application:

For each level of indentation, use four spaces.


Brace Positioning: Classes, methods, and control structures
(if, for, and while) have their opening braces ` on the same
line as the statement, followed by a space. The closing braces
` are positioned at the beginning of the statement on a new
line.
public class MyClass {

public void myMethod() {

if (condition) {

// code

Maximum Line Length: Although 80 characters is still


frequently advised for source code files, try to keep lines no
longer than 120 characters.

Lines that are blank:

Method definitions are separated by two blank lines.

A method's logical sections are separated by a single blank


line.
The declarations of class variables and the first method are
separated by a single blank line.

Bringing in:

Usually, imports come after the package declaration at the


top of the file.

Group imports (all javax.swing imports together, all


java.util imports together, etc.).

In production code, use explicit imports (import


java.util.ArrayList;) instead of wildcard imports (import
java.util.*).

Whitespace:

Keywords (if (, for (, while ()) are separated by a space.

Binary operators (=, +, -, *, /, ==, >=, etc.) are surrounded by


spaces.
A method name and its opening parenthesis (myMethod())
should not be separated by a space.

Conventions for Naming:

Classes and Interfaces: PascalCase, where each word's


initial letter is capitalized. SkinBeautyApp and
TreatmentCalculator are two examples.

Methods and Fields (variables): camelCase (following words


capitalized, first letter lowercase). Examples include
clientIdField, totalCostBeforeDiscount, and
authenticateUser().

Constants: ALL_CAPS_SNAKE_CASE (all capital letters,


with underscores between words). For instance,
LOYALTY_DISCOUNT_RATE, MAX_ATTEMPTS, and
CORRECT_PASSWORD.

Packages: separated.dot.lowercase. For instance,


com.skinaesthetic.app.
Remarks:

Javadoc Remarks: To document classes, interfaces, and


methods, use /**... */. Describe the goal, the parameters
(@param), and the return values (@return).

Just one line Comments: To explain complex logic inline, use


//.

Block Comments: Although /*... */ is frequently preferred


over // for general code comments, it can be used for multi-
line comments.

Readability: Give priority to code that is clear and simple.


Divide difficult tasks into smaller, more doable steps. Make
use of names that have meaning. Use named constants
instead of "magic numbers."
8. Improving the Initial Algorithm and Using an IDE (Java)
to Manage Development
For Java GUI development, using an IDE (such as IntelliJ
IDEA, Eclipse, or NetBeans) is essential because it makes
managing and improving algorithms and code more
efficient.

8.1. Finding and Fixing Logical Mistakes in the Initial


Algorithm
Flow Specific to the GUI: Sequential input is frequently
implied by the algorithm (pseudocode). User interaction in a
graphical user interface is event-driven. Making
assumptions about the order of the inputs could lead to a
logical error.

Improvement: By creating a clear GUI flow—authentication


first, calculation second—the algorithm is subtly improved.
The code makes sure that the computation is only available
after authentication.

IDE Role: The IDE's visual debugger helps trace the flow
triggered by button clicks. If a button isn't responding or is
performing an incorrect action, the debugger shows which
ActionListener is invoked and where the logic deviates from
the intended algorithm.
at the pseudocode doesn't explain how to deal with empty or
non-numeric input from a JTextField.

Improvement: When parsing numeric inputs and checking


for empty strings, the Java code incorporates explicit try-
catch blocks for NumberFormatException. JOptionPane is
used to display error messages.

The role of the IDE is to quickly identify the need for specific
exception handling by running the application with invalid
inputs and monitoring the console output (for stack traces)
or the debugger's execution path. Common input validation
logic can then be extracted into helper methods with the aid
of the IDE's refactoring tools.

8.2. Troubleshooting Program Errors


Strong debugging features that are necessary for GUI
applications are provided by Java IDEs:

Breakpoints: To halt execution, set breakpoints on


particular lines (for example, at the beginning of an
actionPerformed method or within calculation logic).

Step-Through Execution: Step Out to end a method, Step


Into to enter method calls, and Step Over to execute lines
one after the other. This is essential for comprehending the
data flow between the GUI and logic as well as the event-
driven flow.

Variable Inspection: All variables in scope, including the


states of GUI components (such as JTextField.getText() and
JPasswordField.getPassword()), are displayed in the
"Variables" window. This makes it easier to confirm that
input is accurately recorded and that computations are
proceeding as planned.
Watches: Even if they aren't specifically in the current
scope, you can add expressions to "Watches" to track their
values while the program runs.

The call stack, which is essential for comprehending the


event propagation chain in a graphical user interface,
displays the order of method calls that resulted in the
current execution point.

Exception Handling Tools: IDEs allow you to set


breakpoints on exceptions to instantly jump to the source of
the error, highlight unhandled exceptions, and display stack
traces.
Conditional Breakpoints: These are helpful for isolating
particular scenarios because they can be configured to only
activate when a certain condition is met (e.g., attempts ==
MAX_ATTEMPTS).

8.3: Tracking and Monitoring Algorithm (Code) Changes


with Version Control in the IDE Java IDEs are easily
integrated with Git, offering a visual version control
interface.

Initial Commit: git commit -m "Initial GUI setup and


authentication panel" is the first commit made after the
basic project structure and initial GUI have been
established.

Branching for Features: New branches (git branch


feature/treatment-selection) can be made to work on
features separately in order to add new GUI elements (such
as treatment selection) or improve computations.

Making Incremental Changes: git commit -m "Implement


calculation logic for treatments" is an example of a small,
logical change that is regularly made with unambiguous
messages.
Viewing History and Diff: The Git view in the IDE makes it
possible to examine commit history, compare various file
versions side by side to see precise changes, and comprehend
how the code has changed over time.

Reverting or cherry-picking: The IDE offers tools to go back


to a prior commit or cherry-pick particular changes if a
change causes problems.

Resolving merge conflicts, staging changes, and merging


branches back into the main development line are all made
easier by the IDE.
8.4: Optimizing the Algorithm (Code) with Performance
Monitoring Tools
Even though the application is small, integrated profiling
tools are available in IDEs for larger Java applications.

Java Profilers: IDEs may come with built-in profilers or


integrate with JVM profiling tools (such as Java VisualVM,
YourKit, and JProfiler). These instruments are capable of:

CPU profiling: Find the processes that use the CPU the
most, emphasizing any bottlenecks in the GUI rendering or
calculation logic.
Memory Profiling: This is essential for GUI applications that
run for extended periods of time because it can identify
memory leaks or excessive memory usage.

Thread Profiling: Keep an eye on thread activity to make


sure that lengthy tasks aren't obstructing the EDT.

Refining Algorithm: The algorithm (and its code


implementation) could be improved if profiling showed, for
example, that the discount calculation was surprisingly slow
(for example, because of inefficient data structures or
repeated computations).

8.5. Improving and Streamlining the Algorithm Using


Various Data Structures and Code Constructs: The best way
to retrieve prices based on treatment names is to use
HashMap for TREATMENT_PRICES, which offers
efficient (average O(1)) lookup.

Modularization is the process of dividing an application into


discrete classes, such as a main JFrame class and a separate
Calculator class for business logic. This enhances
maintainability and facilitates testing and reasoning about
each component.
Constants: The code is easier to read and modify when
constants (such as CORRECT_PASSWORD,
MAX_ATTEMPTS, and LOYALTY_DISCOUNT_RATE)
are defined.

Helper Methods: Code reuse and readability are enhanced


by the creation of brief, targeted helper methods (such as
displayMessage and clearFields).

Java 8+'s Stream API: This feature could be used for more
succinct and possibly parallelizable operations for more
complex data processing (such as filtering lists of
treatments), but for this particular application, traditional
loops are perfectly clear and efficient.
9. Final Annotated Source Code and Working Application
The following Java code implements the algorithms defined
above, incorporating the discussed enhancements and
adhering to the specified coding standards. It provides a
simple Swing-based GUI for interaction.

Colculation
The process from conceptual algorithm design to a working
Python application for the Skin Beauty Aesthetic Center has
been covered in detail in this report. A solid blueprint was
created by first outlining precise pseudocode algorithms for
cost computation and user authentication. Python was
selected as the implementation language because of its rapid
development capabilities, large library, and ease of reading.

Logical structures were directly translated during the


conversion process, with the required modifications made
for Python's syntax, data types, and reliable error handling.
Try-except blocks and unambiguous prompts were used to
solve issues like type conversion errors and controlling user
input. Following PEP 8 coding guidelines guarantees that the
code is easily comprehensible and maintainable.
2. Algorithm Definition
The core of the Skin Beauty Aesthetic Centre application relies on two primary algorithms: User
Authentication and Treatment Cost Calculation with Discount Application. The logical flow of
these algorithms remains consistent, regardless of the chosen programming paradigm or
interface.

2.1. Algorithm 1: User Authentication

This algorithm controls access to the system, allowing a maximum of three login attempts.

Design Tool: Pseudocode

// Algorithm: User Authentication


// Objective: Authenticate user with a password, allowing 3 attempts.

FUNCTION AuthenticateUser(userPasswordInput)
SET correctPassword = "password123" // Example password
SET maxAttempts = 3
SET attempts = 0
SET isAuthenticated = FALSE

WHILE attempts < maxAttempts AND isAuthenticated is FALSE


// In GUI, userPasswordInput would come from a JPasswordField
// This loop would effectively be handled by event listeners and an
internal counter.
// For CLI, PROMPT "Enter password: " and READ userPassword

IF userPasswordInput == correctPassword THEN


SET isAuthenticated = TRUE
DISPLAY "Authentication successful!"
ELSE
INCREMENT attempts
IF attempts < maxAttempts THEN
DISPLAY "Incorrect password. You have " + (maxAttempts -
attempts) + " attempts remaining."
ELSE
DISPLAY "Incorrect password. No attempts remaining. Access
locked."
END IF
END IF
END WHILE

RETURN isAuthenticated
END FUNCTION

2.2. Algorithm 2: Treatment Cost Calculation and Discount Application


This algorithm calculates the total cost of treatments, applies tiered discounts based on spending,
and an additional loyalty discount.

Design Tool: Pseudocode

// Algorithm: Treatment Cost Calculation and Discount Application


// Objective: Calculate total treatment cost, apply spending and loyalty
discounts.

FUNCTION CalculateClientCost(clientID, clientName, membershipDuration,


selectedTreatmentsData)
// GUI adaptation: Authentication is handled separately before this
function is called.
// If NOT AuthenticateUser() THEN
// DISPLAY "System access denied. Exiting."
// RETURN
// END IF

// Inputs now come as parameters from GUI fields:


// PROMPT "Enter Client ID: " READ clientID
// PROMPT "Enter Client Name: " READ clientName
// PROMPT "Enter Membership Duration (months): " READ membershipDuration
// PROMPT "Enter selected treatments data (from GUI selections): " READ
selectedTreatmentsData

SET treatmentPrices = { // Dictionary/Map for treatment prices


"Chemical Peel": 175.00,
"Microneedling": 275.00,
"PRP Therapy": 100.00,
"HIFU Treatment": 400.00,
"Hair Treatment": 100.00,
"Manicure": 20.00,
"Pedicure": 25.00
}

SET totalCostBeforeDiscount = 0.00


SET itemizedTreatments = [] // List to store selected treatments and their
costs

// Loop through the data provided by the GUI for selected treatments
FOR EACH treatmentEntry IN selectedTreatmentsData // e.g., [{name:
"Chemical Peel", sessions: 2}, ...]
SET selectedTreatmentName = treatmentEntry.name
SET numberOfSessions = treatmentEntry.sessions

IF selectedTreatmentName IS IN treatmentPrices THEN


SET treatmentCost = treatmentPrices[selectedTreatmentName] *
numberOfSessions
ADD {name: selectedTreatmentName, sessions: numberOfSessions,
cost: treatmentCost} TO itemizedTreatments
ADD treatmentCost TO totalCostBeforeDiscount
ELSE
// This scenario should be rare with GUI pickers, but handling is
good practice
DISPLAY "Invalid treatment name encountered: " +
selectedTreatmentName
END IF
END FOR

// Calculate spending discount


// The highest applicable spending discount tier is chosen.
SET spendingDiscountRate = 0.00
IF totalCostBeforeDiscount > 1500.00 THEN
SET spendingDiscountRate = 0.15 // 15% discount
ELSE IF totalCostBeforeDiscount > 1000.00 THEN
SET spendingDiscountRate = 0.10 // 10% discount
ELSE IF totalCostBeforeDiscount > 500.00 THEN
SET spendingDiscountRate = 0.05 // 5% discount
END IF

// Calculate loyalty discount


// This is an additional discount, applied if membership duration meets
the threshold.
SET loyaltyDiscountRate = 0.00
IF membershipDuration >= 12 THEN
SET loyaltyDiscountRate = 0.05 // 5% additional loyalty discount
END IF

// --- Discount Calculation ---


// Calculate the monetary amount for each discount type based on the total
cost before discount.
SET spendingDiscountAmount = totalCostBeforeDiscount *
spendingDiscountRate
SET loyaltyDiscountAmount = totalCostBeforeDiscount * loyaltyDiscountRate

// The total discount is the sum of spending discount and loyalty


discount.
SET totalDiscountAmount = spendingDiscountAmount + loyaltyDiscountAmount

// The final cost is the original total minus the combined discount.
SET totalCostAfterDiscount = totalCostBeforeDiscount - totalDiscountAmount

// Example Calculation:
// Assume totalCostBeforeDiscount = £1200.00, membershipDuration = 15
months
// 1. Spending Discount: totalCostBeforeDiscount (£1200) > £1000, so
spendingDiscountRate = 0.10 (10%)
// spendingDiscountAmount = £1200.00 * 0.10 = £120.00
// 2. Loyalty Discount: membershipDuration (15) >= 12 months, so
loyaltyDiscountRate = 0.05 (5%)
// loyaltyDiscountAmount = £1200.00 * 0.05 = £60.00
// 3. Total Discount Amount = spendingDiscountAmount +
loyaltyDiscountAmount = £120.00 + £60.00 = £180.00
// 4. Total Cost After Discount = totalCostBeforeDiscount -
totalDiscountAmount = £1200.00 - £180.00 = £1020.00
// ----------------------------

// Output results to GUI (e.g., JTextArea or JLabels)


DISPLAY "--- Client Monthly Statement ---"
DISPLAY "Client Name: " + clientName
DISPLAY "Client ID: " + clientID
DISPLAY "Membership Duration: " + membershipDuration + " months"
DISPLAY "Itemised Treatments:"
FOR EACH treatment IN itemizedTreatments
DISPLAY "- " + treatment.name + " (" + treatment.sessions + "
sessions): £" + FORMAT_TO_TWO_DECIMALS(treatment.cost)
END FOR
DISPLAY "Total Cost Before Discount: £" +
FORMAT_TO_TWO_DECIMALS(totalCostBeforeDiscount)
DISPLAY "Spending Discount: £" +
FORMAT_TO_TWO_DECIMALS(spendingDiscountAmount) + " (" +
FORMAT_PERCENTAGE(spendingDiscountRate) + "%)"
DISPLAY "Loyalty Discount: £" +
FORMAT_TO_TWO_DECIMALS(loyaltyDiscountAmount) + " (" +
FORMAT_PERCENTAGE(loyaltyDiscountRate) + "%)"
DISPLAY "Total Discount Amount: £" +
FORMAT_TO_TWO_DECIMALS(totalDiscountAmount)
DISPLAY "Total Cost After Discount: £" +
FORMAT_TO_TWO_DECIMALS(totalCostAfterDiscount)
DISPLAY "--------------------------------"

END FUNCTION

// Helper function for formatting


FUNCTION FORMAT_TO_TWO_DECIMALS(number)
RETURN ROUND(number, 2) // Rounds to two decimal places
END FUNCTION

FUNCTION FORMAT_PERCENTAGE(decimal)
RETURN (decimal * 100) + "%"
END FUNCTION

3. Outline of Steps Required to Build the Application


Building the Java GUI application involves several key steps, from setting up the development
environment to testing and deployment.

1. Understand Requirements: Thoroughly review the client's needs, identifying all inputs,
processes, and required outputs.
2. Algorithm Design: Develop detailed algorithms (e.g., pseudocode, flowcharts) for each
core functionality (authentication, calculation, discounting). (Completed in Section 2).
3. Choose Programming Language (Java) and IDE: Select Java due to its platform
independence and robust GUI frameworks, and an IDE like IntelliJ IDEA or Eclipse for
development.
4. Design GUI Layout: Sketch out the user interface, identifying necessary components
(text fields, buttons, labels, lists/tables for treatments).
5. Set Up Project Structure: Create a well-organised Java project with appropriate
packages for different concerns (e.g., ui, logic, model).
6. Implement GUI Components: Write Java code using Swing to create the main window
(JFrame), panels (JPanel), input fields (JTextField, JPasswordField), buttons
(JButton), and display areas (JTextArea, JLabel).
7. Implement Event Handling: Attach ActionListener to buttons and other interactive
elements to respond to user actions. This is key for event-driven programming.
8. Implement User Authentication Logic: Code the password authentication logic,
including attempts tracking and lockout, integrated with GUI input (JPasswordField) and
output (JLabel/JOptionPane for messages).
9. Implement Data Input Logic (GUI): Retrieve data from GUI components for client ID,
name, selected treatments (e.g., from checkboxes or a table), number of sessions, and
membership duration. This will involve parsing text from JTextFields.
10. Implement Core Calculation Logic: Develop Java classes/methods to calculate the total
cost of treatments based on selected services and their prices, detached from the GUI for
better separation of concerns.
11. Implement Discount Logic: Code the conditional logic for applying spending-tiered
discounts and loyalty discounts as methods within the calculation logic.
12. Update GUI with Output: Populate GUI elements (e.g., JTextArea or JLabels) with
the itemised list, total costs, discount amounts, and final cost.
13. Error Handling (Java Exceptions): Implement try-catch blocks to gracefully handle
invalid inputs (e.g., NumberFormatException when parsing non-numeric text) and
display user-friendly error messages in dialogs (JOptionPane).
14. Testing: Conduct unit tests for individual logic classes and integration tests for the entire
GUI application flow.
15. Debugging: Use IDE features to identify and fix any logical or syntax errors, particularly
with event handling.
16. Refinement and Optimisation: Improve code efficiency, readability, and user
experience (e.g., clear input validation feedback, responsive layout).
17. Documentation and Comments: Add Javadoc comments to classes and methods, and
inline comments for complex logic.
18. Version Control: Utilise an IDE's integrated version control (e.g., Git) to track changes
and manage different versions of the code.

4. Converting the Algorithm into a Working Program


4.1. Identification of a Suitable Programming Language

For this application, Java has been chosen as the programming language, specifically utilising its
Swing library for the GUI.

Reasons for choosing Java (with Swing):

 Platform Independence (WORA): Java's "Write Once, Run Anywhere" principle


ensures the application can run on various operating systems without modification,
provided a Java Virtual Machine (JVM) is installed.
 Robustness and Scalability: Java is a strongly-typed language, which helps catch errors
at compile time, leading to more robust applications. It's well-suited for larger, more
complex systems.
 Object-Oriented Paradigm: Java is inherently object-oriented, which aligns well with
building modular and maintainable GUI applications.
 Rich Ecosystem and Libraries: Java has a vast ecosystem, including the Swing
framework for building powerful desktop GUIs.
 IDE Support: Java development is highly supported by powerful IDEs (e.g., IntelliJ
IDEA, Eclipse, NetBeans) that offer excellent features for GUI design, debugging,
refactoring, and project management.
 Event-Driven Programming: Swing naturally supports event-driven programming,
which is essential for interactive GUIs where actions are triggered by user events (button
clicks, text input).

4.2. Description of Steps for Conversion

The conversion from pseudocode to Java code involves translating each logical step and
construct into its equivalent Java syntax, with significant adaptations for the GUI.

1. Classes and Objects: Java is object-oriented. Instead of just functions, we'll have classes
(e.g., SkinBeautyApp, AuthenticationPanel, CalculationPanel,
TreatmentCalculator). This modularises the application.
o FUNCTION AuthenticateUser() becomes a method within an authentication
class or the main application class.
o SET treatmentPrices = {...} becomes a static final Map<String,
Double> in a utility class or the main application class.
2. Variables and Data Types: Pseudocode variables are mapped to Java variables with
explicit type declarations (String, int, double, boolean, List<Map<String,
Object>>).
o SET isAuthenticated = FALSE becomes boolean isAuthenticated =
false;
o SET totalCostBeforeDiscount = 0.00 becomes double
totalCostBeforeDiscount = 0.00;
o SET itemizedTreatments = [] becomes List<Map<String, Object>>
itemizedTreatments = new ArrayList<>(); (Java's equivalent of a list of
objects/maps).
3. Control Structures:
o Conditional Statements (IF-ELSE IF-ELSE): These translate directly to Java's
if-else if-else blocks, similar to Python.
o Loops (WHILE, FOR EACH):
 WHILE attempts < maxAttempts AND isAuthenticated is FALSE
becomes while (attempts < MAX_ATTEMPTS && !isAuthenticated)
 WHILE TRUE for continuous input in pseudocode often implies a
continuous GUI input loop, but in Java GUI, it means that input fields are
constantly available, and processing happens on button clicks.
 FOR EACH treatmentEntry IN selectedTreatmentsData becomes a
Java enhanced for loop: for (Map<String, Object>
treatmentEntry : selectedTreatmentsData)
4. Input/Output (GUI-centric): This is the most significant change.
o PROMPT "Enter password: " and READ userPassword are replaced by fetching
text from a JPasswordField and JTextField respectively.
o DISPLAY "Authentication successful!" and other output messages are
handled by setting text on JLabels, appending to JTextAreas, or showing
JOptionPane dialogs.
o User input for selecting treatments will involve JCheckBoxes, JComboBoxes, or
populating a JTable, requiring event handling to capture selections and
quantities.
5. Arithmetic Operations: Standard arithmetic operators (+, -, *, /) are identical.
6. String Formatting: The pseudocode's FORMAT_TO_TWO_DECIMALS and
FORMAT_PERCENTAGE are implemented using Java's String.format() method,
DecimalFormat from java.text, or NumberFormat for currency.
7. Error Handling (Exceptions): Instead of just checking for invalid input, Java uses try-
catch blocks to handle runtime exceptions like NumberFormatException when
converting String input from JTextField to int or double.

5. Analysis of the Relationship Between Algorithm and


Program Code
The relationship between the algorithm and the program code is symbiotic: the algorithm
provides the logical blueprint, while the program code is the concrete implementation. For a GUI
application, the underlying algorithms remain the same, but their triggering and data flow are
fundamentally different.

5.1. Parts of the Algorithm that Would Remain the Same

 Core Logical Flow: The sequential steps for password authentication (check, increment
attempt, lock if max attempts reached) remain the same. The order of operations for
calculating total cost, determining discount rates, and applying them remains consistent.
 Conditional Logic for Discounts: The if-else if-else structure for tiered spending
discounts and the separate if check for loyalty membership are directly translated.
 Mathematical Formulas: The calculations for totalCostBeforeDiscount,
spendingDiscountAmount, loyaltyDiscountAmount, totalDiscountAmount, and
totalCostAfterDiscount are identical.
 Data Relationships: The association of treatment names with prices and the structure of
itemized treatments (name, sessions, cost) are preserved, likely using Java Maps and
Lists.

5.2. Changes that Would Have to Be Made (Adaptations for Java & GUI)

 Paradigm Shift (Event-Driven): The most significant change is from


sequential/procedural input in pseudocode to an event-driven model. User actions (button
clicks, text field changes) trigger specific methods (actionPerformed in an
ActionListener), rather than the program waiting for READ commands.
 GUI Component Interaction:
o Instead of input(), data is retrieved from JTextField.getText(),
JPasswordField.getPassword(), or selected items from
JComboBox/JCheckBox.
o Instead of print(), output is directed to JLabel.setText(),
JTextArea.append(), or JOptionPane.showMessageDialog().
 Separation of Concerns: Good GUI design dictates separating the business logic
(calculations, authentication rules) from the presentation logic (GUI components, layout).
The pseudocode functions might be implemented as methods in a Calculator class,
separate from the JFrame class.
 Explicit Type Declarations: Java is statically typed, requiring explicit declaration of
variable types (e.g., String, int, double, boolean, List, Map).
 Object-Oriented Design: The application will be structured into multiple classes (e.g.,
AppFrame, AuthPanel, CalculationPanel, Treatment, Client).
 Exception Handling: Java uses checked and unchecked exceptions. try-catch blocks
are mandatory for operations that can throw exceptions, like NumberFormatException
when parsing user input strings to numbers.
 Collection Framework Usage: Pseudocode's conceptual "lists" and "dictionaries"
translate to Java's ArrayList, HashMap, LinkedHashMap, etc., from the java.util
package.
 Layout Management: Designing the visual arrangement of GUI components requires
using Java's layout managers (e.g., BorderLayout, FlowLayout, GridLayout,
GridBagLayout) to ensure responsiveness and proper sizing.
 Resource Management: For file I/O or database connections (not directly in this scope,
but common in Java), explicit resource closing via try-with-resources is a best
practice.
 Imports: Necessary Java packages (e.g., javax.swing.*, java.awt.*, java.util.*,
java.text.*) must be imported.

6. Analysis of Possible Challenges When Converting the


Algorithm to Program Code (Java & GUI)
Converting the algorithm to a Java GUI application introduces several challenges compared to a
simple command-line version:

1. GUI Layout and Responsiveness:


o Challenge: Arranging components aesthetically and ensuring they scale well
across different screen sizes.
o Issue: Poor layout can lead to cluttered, unreadable, or unusable interfaces (e.g.,
components overlapping, too small).
o Solution: Careful selection and combination of Swing layout managers
(GridBagLayout for complex forms, BorderLayout for main structure,
FlowLayout for simple rows/columns). Using JPanels to group related
components and apply different layouts within them.
2. Event Handling Complexity:
o Challenge: Managing user interactions (button clicks, text field changes) and
ensuring the correct logic is triggered.
o Issue: Incorrectly wired ActionListeners or complex event chains can lead to
unexpected behavior, unresponsive UI, or race conditions if not careful with
threading (less of an issue for this simple app, but relevant for advanced GUIs).
o Solution: Implement ActionListener interfaces for buttons and ensure proper
delegation of tasks to back-end logic methods. Using inner classes or lambda
expressions for listeners can keep related code together.
3. Data Type Conversion and Validation (GUI Input):
o Challenge: All input from JTextFields is String. It must be parsed to int or
double for calculations.
o Issue: NumberFormatException will occur if users enter non-numeric text,
crashing the application if not handled.
o Solution: Use try-catch (NumberFormatException) blocks around
Integer.parseInt() or Double.parseDouble(). Display user-friendly error
messages (e.g., JOptionPane.showMessageDialog) if input is invalid. Also,
validate for empty inputs.
4. Maintaining Separation of Concerns:
o Challenge: It's easy to mix GUI code with business logic, making the code harder
to read, test, and maintain.
o Issue: "Spaghetti code" where UI updates are intertwined with calculation logic.
o Solution: Implement a clear separation (e.g., Model-View-Controller pattern
conceptually). Create dedicated classes for CalculationLogic,
AuthenticationService, and a UIFrame class. The UI class collects input and
passes it to the logic classes, then receives results to update the display.
5. Thread Safety (Minor for this app):
o Challenge: GUI updates in Swing must occur on the Event Dispatch Thread
(EDT). Long-running tasks on the EDT will freeze the UI.
o Issue: While less critical for small calculations, if the application involved heavy
computations or network calls, performing them directly in an ActionListener
would cause the UI to become unresponsive.
o Solution: For more complex applications, use SwingWorker or other concurrency
mechanisms to perform long tasks in a background thread and update the UI
safely on the EDT. (Not strictly needed for this project, but a general Java GUI
challenge).
6. Compilation and Dependencies:
o Challenge: Ensuring all necessary Java classes are correctly compiled and that
the JVM can find all required libraries (though Swing is built-in).
o Issue: ClassNotFoundException or compilation errors if packages are not
imported or classes are not correctly structured.
o Solution: Using an IDE simplifies this greatly by managing classpaths and
compilation automatically. Proper package structuring (package
com.skinaesthetic.app;) helps organise code.
7. Explanation of Coding Standards Used in Source Code
(Java)
Adhering to coding standards is crucial for code readability, maintainability, and collaboration.
For this Java application, the following coding standards, largely based on Oracle's Java Code
Conventions, have been applied:

 Indentation: Use 4 spaces per indentation level.


 Brace Placement: Opening braces { for classes, methods, and control structures (if,
for, while) are placed on the same line as the statement, followed by a space. Closing
braces } are on a new line, aligned with the start of the statement.
 public class MyClass {
 public void myMethod() {
 if (condition) {
 // code
 }
 }
 }

 Maximum Line Length: Aim for a maximum of 120 characters per line, though 80 is
often still recommended for source code files.
 Blank Lines:
o Two blank lines between method definitions.
o One blank line to separate logical sections within a method.
o One blank line between class variable declarations and the first method.
 Imports:
o Imports are typically placed at the top of the file, after the package declaration.
o Group imports (e.g., all javax.swing imports together, all java.util imports
together).
o Avoid wildcard imports (import java.util.*) in production code; prefer
explicit imports (import java.util.ArrayList;).
 Whitespace:
o Space after keywords (if (, for (, while ().
o Spaces around binary operators (=, +, -, *, /, ==, >=, etc.).
o No space between a method name and its opening parenthesis (myMethod()).
 Naming Conventions:
o Classes and Interfaces: PascalCase (first letter of each word capitalised).
Example: SkinBeautyApp, TreatmentCalculator.
o Methods and Fields (variables): camelCase (first letter lowercase, subsequent
words capitalised). Example: authenticateUser(),
totalCostBeforeDiscount, clientIdField.
o Constants: ALL_CAPS_SNAKE_CASE (all uppercase, words separated by
underscores). Example: CORRECT_PASSWORD, MAX_ATTEMPTS,
LOYALTY_DISCOUNT_RATE.
o Packages: lowercase.dot.separated. Example: com.skinaesthetic.app.
 Comments:
o Javadoc Comments: Use /** ... */ for documenting classes, interfaces, and
methods. Explain purpose, parameters (@param), and return values (@return).
o Single-line Comments: Use // for inline explanations of complex logic.
o Block Comments: Use /* ... */ for multi-line comments, though often less
preferred than // for general code comments.
 Readability: Prioritise clear and concise code. Break down complex operations into
smaller, manageable methods. Use meaningful names. Avoid "magic numbers" by using
named constants.

8. Enhancing the Original Algorithm and Managing


Development with an IDE (Java)
Using an IDE (like IntelliJ IDEA, Eclipse, or NetBeans) is critical for Java GUI development,
enabling efficient management and enhancement of algorithms and code.

8.1. Identifying and Solving Logical Errors in the Original Algorithm

 GUI-Specific Flow: The algorithm (pseudocode) often implies sequential input. In a


GUI, user interaction is event-driven. A logical error might occur if assumptions about
input order are made.
o Enhancement: The algorithm is implicitly enhanced by designing a clear GUI
flow: authentication first, then calculation. The code ensures calculation is only
accessible post-authentication.
o IDE Role: The IDE's visual debugger helps trace the flow triggered by button
clicks. If a button isn't responding or is performing an incorrect action, the
debugger shows which ActionListener is invoked and where the logic deviates
from the intended algorithm.
 Input Validation Logic: The pseudocode might not specify how to handle non-numeric
or empty input from a JTextField.
o Enhancement: The Java code includes explicit try-catch blocks for
NumberFormatException when parsing numeric inputs and checks for empty
strings. Error messages are displayed via JOptionPane.
o IDE Role: Running the application with invalid inputs and observing the
debugger's execution path or the console output (for stack traces) quickly points
to the need for specific exception handling. The IDE's refactoring tools can then
assist in extracting common input validation logic into helper methods.

8.2. Debugging Errors in the Program

Java IDEs offer powerful debugging capabilities essential for GUI applications:

 Breakpoints: Set breakpoints on specific lines to pause execution (e.g., at the start of an
actionPerformed method, or within calculation logic).
 Step-Through Execution: Step Over to execute lines sequentially, Step Into to enter
method calls, Step Out to exit a method. This is crucial for understanding the event-
driven flow and how data moves between GUI and logic.
 Variable Inspection: The "Variables" window shows the current state of all variables in
scope, including GUI component states (e.g., JTextField.getText(),
JPasswordField.getPassword()). This helps verify that input is correctly captured and
calculations are progressing as expected.
 Watches: Add expressions to "Watches" to monitor their values as the program executes,
even if they're not explicitly in the current scope.
 Call Stack: Shows the sequence of method calls that led to the current execution point,
which is invaluable for understanding the event propagation chain in a GUI.
 Exception Handling Tools: IDEs highlight unhandled exceptions, show stack traces, and
allow setting breakpoints on exceptions to immediately jump to the origin of the error.
 Conditional Breakpoints: Breakpoints can be set to activate only when a specific
condition is met (e.g., attempts == MAX_ATTEMPTS), useful for isolating specific
scenarios.

8.3. Using Version Control within the IDE to Track and Monitor Changes in the
Algorithm (Code)

Java IDEs seamlessly integrate with Git, providing a visual interface for version control.

 Initial Commit: After setting up the basic project structure and initial GUI, a first
commit is made (git commit -m "Initial GUI setup and authentication
panel").
 Branching for Features: For adding new GUI components (e.g., treatment selection) or
refining calculations, new branches (git branch feature/treatment-selection) can
be created to work on features in isolation.
 Committing Incremental Changes: Small, logical changes are committed frequently
with clear messages (e.g., git commit -m "Implement calculation logic for
treatments").
 Viewing History and Diff: The IDE's Git view allows inspecting commit history,
comparing different versions of a file side-by-side to see exact changes, and
understanding the evolution of the code.
 Reverting/Cherry-picking: If a change introduces an issue, the IDE provides tools to
revert to a previous commit or cherry-pick specific changes.
 Staging and Merging: The IDE simplifies staging changes, resolving merge conflicts,
and merging branches back into the main development line.

8.4. Using Performance Monitoring Tools to Optimise the Algorithm (Code)

While the application is small, for larger Java applications, IDEs offer integrated profiling tools.

 Java Profilers: IDEs can integrate with JVM profiling tools (like Java VisualVM,
YourKit, JProfiler) or have built-in profilers. These tools can:
o CPU Profiling: Identify methods that consume the most CPU time, highlighting
bottlenecks in calculation logic or GUI rendering.
o Memory Profiling: Detect memory leaks or excessive memory consumption,
which is crucial for long-running GUI applications.
o Thread Profiling: Monitor thread activity, ensuring the EDT isn't blocked by
long-running tasks.
 Refining Algorithm: If profiling revealed, for instance, that the discount calculation was
unexpectedly slow (e.g., due to inefficient data structures or repeated computations), the
algorithm (and its code implementation) could be refined (e.g., pre-calculating values,
optimising loops, using more efficient collections).

8.5. Refining and Optimising the Algorithm Using Different Code Constructs

 Data Structures: Using HashMap for TREATMENT_PRICES provides efficient (average


O(1)) lookup, which is optimal for retrieving prices based on treatment names.
 Modularisation: Breaking the application into distinct classes (e.g., a main JFrame class,
a separate Calculator class for business logic) improves maintainability and makes each
component easier to test and reason about.
 Constants: Defining constants (e.g., CORRECT_PASSWORD, MAX_ATTEMPTS,
LOYALTY_DISCOUNT_RATE) makes the code more readable and easier to modify.
 Helper Methods: Creating small, focused helper methods (e.g., displayMessage,
clearFields) improves code reuse and readability.
 Stream API (Java 8+): For more complex data processing (e.g., filtering lists of
treatments), Java's Stream API could be used for more concise and potentially
parallelisable operations, although for this specific application, traditional loops are
perfectly clear and efficient.

9. Final Annotated Source Code and Working Application


The following Java code implements the algorithms defined above, incorporating the discussed
enhancements and adhering to the specified coding standards. It provides a simple Swing-based
GUI for interaction.
PRINT "Incorrect Password"
IF attempts == 3 THEN
PRINT "Access Denied"
END
INPUT client ID, name, membership duration

DISPLAY list of available treatments and prices


INPUT number of treatments selected
SET total_cost to 0

FOR each treatment


INPUT treatment name and amount
RETRIEVE price from treatment list
CALCULATE cost = price * amount
ADD cost to total_cost
SAVE treatment information
IF total_cost > 1500 THEN discount = 0.15

ELSE IF total_cost > 1000 THEN discount = 0.10


ELSE IF total_cost > 500 THEN discount = 0.05
ELSE discount = 0.00
IF membership_months >= 12 THEN ADD 0.05 to discount

CALCULATE discount_amount = total_cost * discount

CALCULATE final_cost = total_cost - discount_amount


DISPLAY client name

DISPLAY itemised list of treatments and costs


DISPLAY total_cost, discount_amount, final_cost
END

________________________________________
2. Steps Required to Build the Application
To develop a working application based on the algorithm, the following steps were
followed:
Step 1: Requirement Analysis
• Clarify the purpose of the application: user authentication, treatment selection,
discount calculation, and invoice generation.
• Specify expected inputs (e.g. password, client information, treatment details)
and outputs (formatted invoice).
Step 2: Design Algorithm
• Use pseudocode (see Section 1) to break down the logic into concise, sequential
steps.
• Identify decision points such as discount qualification and
authentication verification.
Step 3: Choose Development Tools
• Select a suitable programming language and development environment.
Step 4: Set up ID
• Create a new project in PyCharm.
• Install Python 3.10 interpreter.
• Organize project files (main.py, resources, test files).
Step 5: Implement and Test Modules
• Authentication module
• Treatment selection and input module
• Discount application logic
• Invoice output formatting
Step 6: Debug, Optimize, and Document
• Utilize IDE tools (debugger, profiler) to discover and resolve issues.
• Apply code standards for readability and maintainability.
• Comment and annotate final source code.
________________________________________
3. Translating the Algorithm into a Working Program
Programming Language Used: Python
Why Python?
• Easy syntax for professionals and beginners
• Support for basic structures (lists, dictionaries)
• Precise floating-point arithmetic
• Robust IDE support for optimization and debugging
• Quick development for console-based programs
Conversion Process
Algorithm Step Code Translation
WHILE attempts < 3 Implemented as a while loop with counter
IF password == correct_password Direct if condition with equality check
INPUT steps Python input() functions with try-except
Treatment storage List of dictionaries to store name, qty, cost
Discount tiers if-elif structures and logic operations
Output formatting f"£{value:.2f}" for two-decimal places
Additional improvements included:
• Validating user inputs
• Displaying menu-style treatment options
• Incorporating function-based modular code structure (def get_treatments())
________________________________________
4. Algorithm and Program Code Relationship
The translation from the pseudocode algorithm to program code
was generally linear, with some modification required for practical application.
Pseudocode Element Code Implementation Changes
Password input Enhanced feedback and input validation using loops
Treatment loop Extended for treatment validation
Discount logic Added cap to prevent outrageous combined discounts
Input/output operations Enhanced with more meaningful prompts and
formatted output
Data structures Used dictionaries and lists for efficiency.
Parts that Did Not Change
• General control flow: input → process → output
• Tier-based and loyalty discount logic
• Loop structure for multiple treatment entries
Parts That Did Change
• Input handling with exception management improved
• Real-time validation of treatments against a predefined list
• Enhanced formatting using string templates and line spacing
________________________________________
5. Challenges Encountered in Code Conversion
5.1 Input Validation
• Problem: User might enter non-numeric data for quantities or durations.
• Solution: Used try-except blocks and .isdigit() checks to enforce input types.
5.2 Floating-Point Precision
• Problem: Totals like 499.999999 were being printed due to floating-point
rounding.
• Solution: Used round() and format(value, ".2f") throughout.
5.3 Data Structure Management
• Problem: Needed to store treatment names, quantities, and prices dynamically.
• Solution: Used list of dict objects, one per treatment.
5.4 Cumulative Discounts
• Problem: Loyalty and tier discounts combined could reach unreasonable levels.
• Solution: Used min(discount_rate, 0.20) to restrict total discount to 20%.
5.5 Code Repetition
• Issue: Duplicate input/output code blocks.
• Solution: Modularized with custom functions for reuse.
________________________________________
6. Coding Standards Used
The following coding standards were implemented:
Standard Description
PEP 8 Compliance Adhered to naming, spacing, and indentation conventions
Function Naming Employed snake_case for function and variable names
Commenting and Docstrings Utilized for each function and significant logic block
Variable Naming Meaningful and descriptive (e.g., total_cost, client_name)
Modularization Program divided into reusable functions
Error Handling All inputs validated to prevent crashes
Tools Used for Standards:
• Built-in PyCharm linting
• PEP 8 style checker plugin
These standards ensure that the application is readable, testable, and
maintainable by any team member.
________________________________________
7. Refining the Original Algorithm Through the Use of IDE Features
7.1 Debugging Logical Errors
Tools Used:
• PyCharm debugger with line-by-line execution
• Conditional breakpoints for applying discount
Example Repair:
• Calculation error: discounts were being applied before full cost was added
Resolved By: Reordering calculations after treatment loop
7.2 Debugging Program Errors
• Used the variable watch window to track cost totals
• Detected and fixed incorrect variable scoping within loops
• Used print() statements during early development for traceability
7.3 Version Control
• System: Git (via PyCharm)
• Branches established: main (stable), dev (feature testing)
• Sample commit messages:
o fix: corrected faulty discount calculation
o add: input validation for quantity and treatment name
7.4 Performance Monitoring
• Profiler: Used the performance tool in PyCharm to monitor runtime bottlenecks
• Identified unnecessary dictionary lookups and optimized by caching treatment
prices
7.5 Refinement Using Code Constructs
• Replaced duplicate if conditions with dictionary lookups
• Utilized functions for duplicated logic:
o calculate_total_cost()
o apply_discounts()
o print_invoice()
• Added constants for treatment costs for better maintainability
________________________________________
8. Conclusion
The journey of creating a functional application from a well-structured
algorithm comprised multiple stages — from design concept to implementation
and refinement. The algorithm acted as a map, and
Python allowed for the quick conversion to executable code.
The use of an IDE (PyCharm) significantly improved the
development process through the availability of debugging features, version
control, and performance profiling. By adhering strictly to coding standards and
modular design, the final product is a sound, maintainable,
and readily extensible program.
The completed program successfully meets the Skin Beauty Aesthetic Centre's
requirements:
• Secure authentication
• Dynamic treatment input
• Accurate tiered and loyalty-based discount calculation
• Readably formatted invoice output

You might also like