Islamia college
Peshawar
Software Construction
Assignment No:- 2
Prepared By:
Farman Ullah
Roll No:- 221135
BSSE Section (A)
5th semester
Apply defensive Technique in Currency
Conversion
To apply defensive programming techniques in the Currency Converter project, we need to ensure
that the program handles unexpected conditions gracefully, preventing errors and ensuring
robustness. Below are key areas where defensive programming techniques can be applied:
1. Input Validation:
• Validate user input (e.g., the amount entered) to ensure it is a valid number.
• Handle edge cases such as negative amounts or zero amounts.
• Ensure that currency values are selected from the dropdown menu, preventing null
values.
2. Exception Handling:
• Add specific exception handling (e.g., NumberFormatException,
NullPointerException) to handle invalid inputs, empty fields, and unexpected
issues.
• Use try-catch blocks to gracefully catch and report errors without crashing the
application.
3. Preconditions:
• Check preconditions such as ensuring the amountField is not empty before trying to
convert.
• Ensure valid selections for both source and target currencies.
4. Postconditions:
• Check if the result is calculated properly before displaying it.
• Ensure that the result is valid and meaningful.
import [Link].*;
import [Link].*;
import [Link];
import [Link];
/**
* Currency Converter Program.
* This program converts an amount from one currency to another.
* The user selects the source and target currencies, enters an amount,
* and clicks "Convert" to get the result.
*/
public class CurrencyConverter {
private JFrame frame;
private JTextField amountField;
private JTextField resultField;
private JComboBox<String> sourceCurrencyComboBox;
private JComboBox<String> targetCurrencyComboBox;
public static void main(String[] args) {
[Link](CurrencyConverter::new);
/**
* Constructor to initialize the Currency Converter GUI.
*/
public CurrencyConverter() {
initializeUI();
/**
* Initializes and sets up the GUI components.
*/
private void initializeUI() {
frame = new JFrame("Currency Converter");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](500, 350);
[Link](null); // Center the window
[Link](new BorderLayout());
// Main panel with GridBagLayout for better component arrangement
JPanel mainPanel = new JPanel();
[Link](new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
[Link] = new Insets(5, 5, 5, 5); // Padding around components
// Amount input field
JLabel amountLabel = new JLabel("Amount:");
amountField = new JTextField(15);
[Link](amountField);
[Link] = 0;
[Link] = 0;
[Link](amountLabel, gbc);
[Link] = 1;
[Link](amountField, gbc);
// Source currency selection
JLabel sourceCurrencyLabel = new JLabel("From Currency:");
sourceCurrencyComboBox = new JComboBox<>(new String[]{"USD", "EUR",
"GBP", "INR", "PKR", "SAR"});
[Link](sourceCurrencyComboBox);
[Link] = 0;
[Link] = 1;
[Link](sourceCurrencyLabel, gbc);
[Link] = 1;
[Link](sourceCurrencyComboBox, gbc);
// Target currency selection
JLabel targetCurrencyLabel = new JLabel("To Currency:");
targetCurrencyComboBox = new JComboBox<>(new String[]{"USD", "EUR",
"GBP", "INR", "PKR", "SAR"});
[Link](targetCurrencyComboBox);
[Link] = 0;
[Link] = 2;
[Link](targetCurrencyLabel, gbc);
[Link] = 1;
[Link](targetCurrencyComboBox, gbc);
// Result field
resultField = new JTextField(15);
[Link](false);
[Link](new Font("Arial", [Link], 14));
[Link](Color.LIGHT_GRAY);
JLabel resultLabel = new JLabel("Converted Amount:");
[Link](resultField);
[Link] = 0;
[Link] = 3;
[Link](resultLabel, gbc);
[Link] = 1;
[Link](resultField, gbc);
// Convert button with icon and style
JButton convertButton = new JButton("Convert");
[Link](new ImageIcon("convert_icon.png")); // Use your own
icon here
[Link](new Color(0x4CAF50)); // Green background
[Link]([Link]);
[Link](new Font("Arial", [Link], 14));
[Link]("Click to convert the entered amount.");
[Link](new ConvertButtonListener());
// Add button to panel
[Link] = 0;
[Link] = 4;
[Link] = 2;
[Link] = [Link];
[Link](convertButton, gbc);
[Link](mainPanel, [Link]);
// Make frame visible
[Link](true);
/**
* ActionListener for handling the convert button click.
*/
private class ConvertButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String amountText = [Link]().trim();
if ([Link]()) {
[Link](frame, "Please enter an amount!",
"Error", JOptionPane.ERROR_MESSAGE);
return;
// Defensive check for invalid characters (only digits and decimal point
allowed)
if (?")) {
[Link](frame, "Invalid amount format! Please
enter a valid number.", "Error", JOptionPane.ERROR_MESSAGE);
return;
try {
double amount = [Link](amountText);
// Defensive programming: Ensure that the amount is positive
if (amount <= 0) {
[Link](frame, "Amount should be greater
than zero.", "Error", JOptionPane.ERROR_MESSAGE);
return;
String sourceCurrency = (String)
[Link]();
String targetCurrency = (String)
[Link]();
// Defensive check: Ensure both source and target currencies are selected
if (sourceCurrency == null || targetCurrency == null) {
[Link](frame, "Please select both source and
target currencies.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
double result = convertCurrency(amount, sourceCurrency,
targetCurrency);
// Defensive check: Ensure that the result is a valid number
if ([Link](result) || [Link](result)) {
[Link](frame, "Conversion error. Please
check the currencies selected.", "Error", JOptionPane.ERROR_MESSAGE);
return;
[Link]([Link]("%.2f %s", result, targetCurrency));
} catch (NumberFormatException ex) {
// Catch any unexpected exceptions related to conversion
[Link](frame, "Unexpected error during
conversion. Please try again.", "Error", JOptionPane.ERROR_MESSAGE);
/**
* Converts the given amount from one currency to another.
* @param amount The amount to be converted.
* @param sourceCurrency The source currency (e.g., USD).
* @param targetCurrency The target currency (e.g., EUR).
* @return The converted amount.
*/
private double convertCurrency(double amount, String sourceCurrency, String
targetCurrency) {
// Simple conversion rates (in real world, use an API for up-to-date rates)
double conversionRate = 1.0;
// USD to other currencies
if ([Link]("USD") && [Link]("EUR")) {
conversionRate = 0.85;
} else if ([Link]("USD") && [Link]("GBP")) {
conversionRate = 0.75;
} else if ([Link]("USD") && [Link]("INR")) {
conversionRate = 74.50; // USD to INR
} else if ([Link]("USD") && [Link]("PKR")) {
conversionRate = 287.50; // USD to PKR (Pakistani Rupee)
} else if ([Link]("USD") && [Link]("SAR")) {
conversionRate = 3.75; // USD to SAR (Saudi Riyal)
} else if ([Link]("EUR") && [Link]("USD")) {
conversionRate = 1.18;
// Add more conversion rates as needed
return amount * conversionRate;
}
Key Defensive Programming Additions:
1. Input Validation:
o The program now checks that the amount entered contains only digits and an
optional decimal point using a regex ([Link]("[0-
9]+(\\.[0-9]{1,2})?")).
o It ensures that the entered amount is a positive number (amount <= 0).
2. Null Checks:
o The program checks whether both the source and target currencies have been
selected (if (sourceCurrency == null || targetCurrency == null)).
3. Error Handling:
o A try-catch block around
Defensive Technique Applied:
• Amount Validation:
o We check if the amount entered by the user is a valid number using a regular
expression (matches("[0-9]+(\\.[0-9]{1,2})?")). This ensures that the
entered amount consists of digits and optionally a decimal point with two
places. Any other input (e.g., letters, special characters) is rejected.
o Why it matters: This prevents invalid inputs like alphabetic characters (which
would throw a NumberFormatException) from being processed and ensures
that only valid numerical values are passed to the conversion logic.
• Empty Input:
• If the amount field is empty, the program shows a message asking the user to enter a
value. This avoids processing a blank value, which would lead to incorrect results or
errors.
• Non-Negative Amount:
• We validate that the amount entered is positive (if (amount <= 0)). A zero or
negative amount wouldn’t make sense in the context of currency conversion, and
checking this ensures that the user doesn't get unexpected or illogical results.
Exception Handling
• Why it's important: Exception handling allows the program to continue running
smoothly, even when it encounters unexpected situations. Instead of crashing the
entire application, the program gracefully handles the error and informs the user of the
problem.
• Defensive Technique Applied:
o Handling NumberFormatException:
▪ If the user enters an invalid amount that cannot be parsed to a number,
a NumberFormatException could be thrown. The program handles
this exception and shows a message asking the user to enter a valid
number.