SlideShare a Scribd company logo
1 of 17
Download to read offline
Simple array Java code.
The “Park-a-lot” parking garage currently operates without any computerized system. The
management has concerns about inefficiencies of sub-optimal usage of parking space (lost
opportunity/profit). Congestion inside the garage is often caused by drivers searching for vacant
spots. Currently, the management monitors the garage occupancy by having employees walk
around the decks to inspect the occupancy of individual spots.
Now you are hired to develop a more advanced system to track and manage occupancy of a
parking garage and allow customers to find and reserve available parking places.
1. There are 50 parking spaces in total in this parking lot garage
2. The occupancy state of each parking spot: “available,” “reserved,” or “occupied”
3. The customer should be able to check the parking space availability by specifying the desired
date and time interval. If the system responds stating that there are available spots, the customer
should be able to make the parking reservation by data and time
4. The customer should be able to modify their existing reservation(s) before the start time of
their particular reservation.
5. The customer should be able to extend their current occupancy of a parking space only before
their current ending time
Solution
// importing all required libraries
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
/*
The CarFrame class is an implementation of the JFrame and
also contains the main method. Usage:
> java CarFrame
Note that the file carData.txt must be in the same directory as
all compiled code.
*/
public class CarFrame extends JFrame
{
public static JTabbedPane index;
public static CarLot myCarLot;
public CarFrame()
{
// setting window properties
this.setSize(Toolkit.getDefaultToolkit().getScreenSize());
this.setDefaultCloseOperation(3);
this.setTitle("Car Park System");
this.setResizable(false);
Color newColor = new Color(0.2f, 0.1f, 0.8f, 0.1f);
// creating Car Lot object
myCarLot = new CarLot(15, "carData.txt");
// building tabbed panel display
index = new JTabbedPane();
index.setBackground(newColor);
final JPanel statusTab = Status.startup();
final JPanel addOrRemoveCarTab = AddOrRemoveCar.startup();
// adding tabs to tabbed panel
index.addTab("Lot Status", statusTab);
index.addTab("Add Or Remove Cars", addOrRemoveCarTab);
// setting content pane
this.getContentPane().add(index);
}
public static void main(String[] args)
{
// initialize frame and set visible
CarFrame main = new CarFrame();
main.setVisible(true);
}
}
class CarLot
{
// class variables
private Vector registeredDrivers;
private Vector parkingStalls;
private String dataFile;
private int maxLotSize;
// constructor
public CarLot(int maxSize, String fileName)
{
registeredDrivers = new Vector();
parkingStalls = new Vector();
maxLotSize = maxSize;
dataFile = fileName;
loadData();
}
public String getDataFileName()
{
return dataFile;
}
public int getMaxSize()
{
return maxLotSize;
}
public int carCount()
{
return parkingStalls.size();
}
// Input: license plate number
// Output: Stall number in parking lot
// Error State: returned String is ""
public String findStallLocation(String licenseNum)
{
String currentStall = "";
String returnVal = "";
for(int i = 0; i < parkingStalls.size(); i++)
{
currentStall = (String)parkingStalls.elementAt(i);
if(licenseNum.equals(currentStall))
{
returnVal = Integer.toString(i);
break;
}
}
return returnVal;
}
// Loads data from file (maintain persistence upon close)
public int loadData()
{
// each row in the data file represents a registered car
// format:
// licensePlateNum|currentlyParked
FileReader file;
BufferedReader buffer;
StringTokenizer tokens;
String currentLine = "";
String licensePlate = "";
String currentlyParked = "";
try
{
file = new FileReader(dataFile);
buffer = new BufferedReader(file);
// read and parse each line in the file
while((currentLine = buffer.readLine()) != null)
{
int returnVal = 0;
tokens = new StringTokenizer(currentLine, "|");
licensePlate = tokens.nextToken();
currentlyParked = tokens.nextToken();
// load all registered drivers
registeredDrivers.addElement(licensePlate);
// load car into stall if status is "Y"
if(currentlyParked.equals("Y"))
{
if(parkingStalls.size() < maxLotSize)
{
parkingStalls.addElement(licensePlate);
}
else
{
returnVal = -1;
}
}
}
}
catch(FileNotFoundException f)
{
return -1;
}
catch(IOException io)
{
return -1;
}
return 0;
}
// Saves status data upon request to data file
public int saveData()
{
FileWriter writer = null;
PrintWriter printer = null;
String currentRecord = "";
String licensePlate = "";
String parkedPlates = "";
String currentlyParked = "";
try
{
writer = new FileWriter(dataFile);
printer = new PrintWriter(writer);
// build data record by parsing Vectors
for(int i = 0; i < registeredDrivers.size(); i++)
{
licensePlate = (String)registeredDrivers.elementAt(i);
currentlyParked = "N";
for(int j = 0; j < parkingStalls.size(); j++)
{
parkedPlates = (String)parkingStalls.elementAt(j);
if(parkedPlates.equals(licensePlate))
{
currentlyParked = "Y";
break;
}
}
currentRecord = licensePlate + "|" + currentlyParked;
// output record to file
printer.println(currentRecord);
}
// close output streams
writer.close();
printer.close();
}
catch(IOException io)
{
return -1;
}
return 0;
}
public boolean carEnter(String licenseNum)
{
String parkedCar = "";
boolean alreadyHere = false;
// Check stalls to see if car is already parked
for(int i = 0; i < parkingStalls.size(); i++)
{
parkedCar = (String)parkingStalls.elementAt(i);
if(parkedCar.equals(licenseNum))
{
alreadyHere = true;
}
}
// car is not already parked
if(!alreadyHere)
{
// space is still available
if(!lotFull())
{
parkingStalls.addElement(licenseNum);
return true;
}
// space not available
else
{
return false;
}
}
// car already parked in lot
else
{
return false;
}
}
public boolean carExit(String licenseNum)
{
boolean returnVal = false; //default return value
String parkedCar = "";
// searching for car in stalls
for(int i = 0; i < parkingStalls.size(); i++)
{
parkedCar = (String)parkingStalls.elementAt(i);
// car found
if(parkedCar.equals(licenseNum))
{
parkingStalls.removeElementAt(i);
returnVal = true;
break;
}
}
return returnVal;
}
public boolean lotFull()
{
// compare stalls occupied to max lot size
if(parkingStalls.size() == maxLotSize)
{
return true;
}
else
{
return false;
}
}
}
/*
Provides the graphical layout for the Status tab
*/
class Status
{
public static JPanel statusTab = new JPanel();
public static JPanel statusScreen1;
static JTextField licensePlateField = new JTextField(20);
// retrieves Status panel and sets visible
static JPanel startup()
{
statusScreen1 = Status.getStatusScreen1();
statusTab.add(statusScreen1);
statusScreen1.setVisible(true);
return statusTab;
}
//defines and retrieves Status panel
static JPanel getStatusScreen1()
{
statusScreen1 = new JPanel(new FlowLayout());
JPanel generalPanel = new JPanel();
generalPanel.setLayout(new BoxLayout(generalPanel,
BoxLayout.Y_AXIS));
generalPanel.add(Box.createVerticalStrut(170));
JPanel holderPanel = new JPanel(new BorderLayout());
holderPanel.setLayout(new BoxLayout(holderPanel,
BoxLayout.Y_AXIS));
JPanel criteriaPanel = new JPanel();
criteriaPanel.setLayout(new BoxLayout(criteriaPanel,
BoxLayout.X_AXIS));
JLabel licensePlateLabel = new JLabel("License Plate Number:");
Font textFont = new Font("SanSerif", Font.PLAIN, 24);
Font textFieldFont = new Font("Serif", Font.PLAIN, 20);
licensePlateLabel.setFont(textFont);
licensePlateField.setFont(textFieldFont);
criteriaPanel.add(Box.createHorizontalStrut(40));
criteriaPanel.add(licensePlateLabel);
criteriaPanel.add(licensePlateField);
criteriaPanel.add(Box.createHorizontalStrut(40));
final JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel,
BoxLayout.X_AXIS));
JButton lotCapacityButton = new JButton("Check Lot Capacity");
JButton saveStateButton = new JButton("Save Lot State");
JButton findStallButton = new JButton("Locate Vehicle");
JButton clearButton = new JButton(" Clear ");
lotCapacityButton.setFont(textFont);
saveStateButton.setFont(textFont);
findStallButton.setFont(textFont);
clearButton.setFont(textFont);
buttonPanel.add(Box.createHorizontalStrut(10));
buttonPanel.add(lotCapacityButton);
buttonPanel.add(saveStateButton);
buttonPanel.add(findStallButton);
buttonPanel.add(clearButton);
holderPanel.add(criteriaPanel);
holderPanel.add(Box.createVerticalStrut(30));
holderPanel.add(buttonPanel);
generalPanel.add(holderPanel);
statusScreen1.add(generalPanel);
statusScreen1.add(Box.createHorizontalStrut(150));
// button listener for lot capacity
lotCapacityButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// Retrieve required information
String licensePlate = licensePlateField.getText().trim();
int totalCapacity = CarFrame.myCarLot.getMaxSize();
int currentlyOccupied = CarFrame.myCarLot.carCount();
int freeSpace = totalCapacity - currentlyOccupied;
// Print dialog box
JOptionPane.showMessageDialog((Component) buttonPanel,
"Total Capacity: " + totalCapacity +
" Currently Occupied: " + currentlyOccupied +
" Free Space: " + freeSpace,
"Current Car Lot Statistics",
JOptionPane.INFORMATION_MESSAGE);
// reset active tab and field data
CarFrame.index.setSelectedIndex(0);
licensePlateField.setText("");
}
});
// button listener for save state
saveStateButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// perform save operation
int result = CarFrame.myCarLot.saveData();
// check if successful and report results
if(result == 0)
{
JOptionPane.showMessageDialog((Component) buttonPanel,
"Data for all registered users has been updated in file: " +
CarFrame.myCarLot.getDataFileName(),
"Data Stored Successfully", JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog((Component) buttonPanel,
"Data could not be stored!",
"Data Extract Failure", JOptionPane.ERROR_MESSAGE);
}
// reset active tab and field data
CarFrame.index.setSelectedIndex(0);
licensePlateField.setText("");
}
});
// button listener for car location search
findStallButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// retrieve input and perform search
String licensePlate = licensePlateField.getText().trim();
String stallNumber =
CarFrame.myCarLot.findStallLocation(licensePlate);
// check operation result and report using dialog boxes
if(!stallNumber.equals(""))
{
JOptionPane.showMessageDialog((Component) buttonPanel,
"Location of car #" + licensePlate + ":" +
" Stall " + stallNumber,
"Car Location Found",
JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog((Component) buttonPanel,
"Location of car #" + licensePlate + ":"
+ "Could not be found." +
" The vehicle is either not registered or not currently
parked.",
"Car Location Found", JOptionPane.ERROR_MESSAGE);
}
// reset active tab and field data
CarFrame.index.setSelectedIndex(0);
licensePlateField.setText("");
}
});
// button listener for clear
clearButton.addActionListener(new ActionListener()
{ public void actionPerformed(ActionEvent e)
{
// reset license plate field
licensePlateField.setText("");
}
});
return statusScreen1;
}
}
/*
Provides the graphical layout for the Add or Remove Car tab
*/
class AddOrRemoveCar
{
public static JPanel addOrRemoveCarTab = new JPanel();
public static JPanel addOrRemoveCarScreen1;
static JTextField licensePlateField = new JTextField(20);
// Retrieves and returns add/remove car panel
static JPanel startup()
{ addOrRemoveCarScreen1 =
AddOrRemoveCar.getAddOrRemoveCarScreen1();
addOrRemoveCarTab.add(addOrRemoveCarScreen1);
addOrRemoveCarScreen1.setVisible(true);
return addOrRemoveCarTab;
}
// Defines and returns graphical components for screen
static JPanel getAddOrRemoveCarScreen1()
{
addOrRemoveCarScreen1 = new JPanel(new FlowLayout());
JPanel generalPanel = new JPanel();
generalPanel.setLayout(new BoxLayout(generalPanel,
BoxLayout.Y_AXIS));
generalPanel.add(Box.createVerticalStrut(170));
JPanel holderPanel = new JPanel(new BorderLayout());
holderPanel.setLayout(new BoxLayout(holderPanel, BoxLayout.X_AXIS));
JPanel criteriaPanel = new JPanel(new FlowLayout());
JLabel licensePlateLabel = new JLabel("License Plate
Number:",
SwingConstants.RIGHT);
Font textFont = new Font("SanSerif", Font.PLAIN, 24);
Font textFieldFont = new Font("Serif", Font.PLAIN, 20);
licensePlateLabel.setFont(textFont);
licensePlateField.setFont(textFieldFont);
criteriaPanel.add(licensePlateLabel);
criteriaPanel.add(licensePlateField);
final JPanel buttonPanel = new JPanel(new FlowLayout());
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
JButton addButton = new JButton("Add Car to Lot");
JButton removeButton = new JButton("Remove Car from Lot");
JButton clearButton = new JButton("Clear Data");
addButton.setFont(textFont);
removeButton.setFont(textFont);
clearButton.setFont(textFont);
buttonPanel.add(Box.createHorizontalStrut(10));
buttonPanel.add(addButton);
buttonPanel.add(removeButton);
buttonPanel.add(clearButton);
holderPanel.add(criteriaPanel);
generalPanel.add(holderPanel);
holderPanel.add(Box.createVerticalStrut(75));
generalPanel.add(buttonPanel);
addOrRemoveCarScreen1.add(generalPanel);
addOrRemoveCarScreen1.add(Box.createHorizontalStrut(100));
// button listener for adding car to lot
addButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String licensePlate = licensePlateField.getText().trim();
// check validity of input
if((licensePlate.length() == 0))
{
JOptionPane.showMessageDialog((Component) buttonPanel,
"Please fill in the field and try again",
"Blank Field",
JOptionPane.ERROR_MESSAGE);
}
else
{
// perform enter operation
boolean result = CarFrame.myCarLot.carEnter(licensePlate);
// check outcome and report results
if(!result)
{
JOptionPane.showMessageDialog((Component) buttonPanel,
"This license plate is either not registered or is already in the
lot. " +
"Please try again.",
"Invalid Operation", JOptionPane.ERROR_MESSAGE);
}
else
{
int another = JOptionPane.showConfirmDialog((Component)
buttonPanel, "The car has been added. Add another car to the lot?",
"Add Car",
JOptionPane.YES_NO_OPTION);
// reset input field
licensePlateField.setText("");
// change tabs based on user input
if(another == JOptionPane.NO_OPTION)
{
CarFrame.index.setSelectedIndex(0);
}
}
}
}
});
// button listener for removing car from lot
removeButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// retrieve input data
String licensePlate = licensePlateField.getText().trim();
// check data validity
if((licensePlate.length() == 0))
{
// invalid
JOptionPane.showMessageDialog((Component) buttonPanel,
"Please fill in the field and try again",
"Blank Field", JOptionPane.ERROR_MESSAGE);
}
else
{
// valid
// perform exit operation
boolean result = CarFrame.myCarLot.carExit(licensePlate);
// check outcome and report results
if(!result)
{
JOptionPane.showMessageDialog((Component) buttonPanel,
"This license plate is invalid or is already in the lot. Please try
again.",
"Invalid Operation", JOptionPane.ERROR_MESSAGE);
}
else
{
int another = JOptionPane.showConfirmDialog((Component)
buttonPanel, "The car has been removed. Remove another car?", "Add
Car",
JOptionPane.YES_NO_OPTION);
licensePlateField.setText("");
if(another == JOptionPane.NO_OPTION)
{
CarFrame.index.setSelectedIndex(0);
}
}
}
}
});
// button listener for clear button
clearButton.addActionListener(new ActionListener()
{ public void actionPerformed(ActionEvent e)
{
// reset text field
licensePlateField.setText("");
}
});
return addOrRemoveCarScreen1;
}
}

More Related Content

Similar to Simple array Java code.The “Park-a-lot” parking garage currently o.pdf

33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good TestsTomek Kaczanowski
 
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...solit
 
Android programming -_pushing_the_limits
Android programming -_pushing_the_limitsAndroid programming -_pushing_the_limits
Android programming -_pushing_the_limitsDroidcon Berlin
 
Goal The goal of this assignment is to help students understand the.pdf
Goal The goal of this assignment is to help students understand the.pdfGoal The goal of this assignment is to help students understand the.pdf
Goal The goal of this assignment is to help students understand the.pdfarsmobiles
 
From android/ java to swift (2)
From android/ java to swift (2)From android/ java to swift (2)
From android/ java to swift (2)allanh0526
 
Exercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera CymbronExercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera Cymbroncymbron
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good TestsTomek Kaczanowski
 
Oleksandr Tolstykh
Oleksandr TolstykhOleksandr Tolstykh
Oleksandr TolstykhCodeFest
 
Appium Automation with Kotlin
Appium Automation with KotlinAppium Automation with Kotlin
Appium Automation with KotlinRapidValue
 
Native Payment - Part 3.pdf
Native Payment - Part 3.pdfNative Payment - Part 3.pdf
Native Payment - Part 3.pdfShaiAlmog1
 
Pro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptPro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptSeok-joon Yun
 
Droidjam 2019 flutter isolates pdf
Droidjam 2019 flutter isolates pdfDroidjam 2019 flutter isolates pdf
Droidjam 2019 flutter isolates pdfAnvith Bhat
 

Similar to Simple array Java code.The “Park-a-lot” parking garage currently o.pdf (20)

33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
 
ETM Server
ETM ServerETM Server
ETM Server
 
Android programming -_pushing_the_limits
Android programming -_pushing_the_limitsAndroid programming -_pushing_the_limits
Android programming -_pushing_the_limits
 
Goal The goal of this assignment is to help students understand the.pdf
Goal The goal of this assignment is to help students understand the.pdfGoal The goal of this assignment is to help students understand the.pdf
Goal The goal of this assignment is to help students understand the.pdf
 
Drools BeJUG 2010
Drools BeJUG 2010Drools BeJUG 2010
Drools BeJUG 2010
 
From android/ java to swift (2)
From android/ java to swift (2)From android/ java to swift (2)
From android/ java to swift (2)
 
JavaScript Lessons 2023
JavaScript Lessons 2023JavaScript Lessons 2023
JavaScript Lessons 2023
 
Exercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera CymbronExercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera Cymbron
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
Android workshop
Android workshopAndroid workshop
Android workshop
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
Oleksandr Tolstykh
Oleksandr TolstykhOleksandr Tolstykh
Oleksandr Tolstykh
 
Appium Automation with Kotlin
Appium Automation with KotlinAppium Automation with Kotlin
Appium Automation with Kotlin
 
Native Payment - Part 3.pdf
Native Payment - Part 3.pdfNative Payment - Part 3.pdf
Native Payment - Part 3.pdf
 
Pro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptPro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScript
 
Event Sourcing with php
Event Sourcing with phpEvent Sourcing with php
Event Sourcing with php
 
Jar chapter 5_part_ii
Jar chapter 5_part_iiJar chapter 5_part_ii
Jar chapter 5_part_ii
 
Droidjam 2019 flutter isolates pdf
Droidjam 2019 flutter isolates pdfDroidjam 2019 flutter isolates pdf
Droidjam 2019 flutter isolates pdf
 

More from fasttracktreding

Which words can be used to describe quantitative research methods (.pdf
Which words can be used to describe quantitative research methods (.pdfWhich words can be used to describe quantitative research methods (.pdf
Which words can be used to describe quantitative research methods (.pdffasttracktreding
 
TRUE OR FALSE when preparing journal entries, the account titles.pdf
TRUE OR FALSE when preparing journal entries, the account titles.pdfTRUE OR FALSE when preparing journal entries, the account titles.pdf
TRUE OR FALSE when preparing journal entries, the account titles.pdffasttracktreding
 
The home and neighborhood environment are critical factors in childr.pdf
The home and neighborhood environment are critical factors in childr.pdfThe home and neighborhood environment are critical factors in childr.pdf
The home and neighborhood environment are critical factors in childr.pdffasttracktreding
 
RNA is hypothesized to have been the genetic material of the original.pdf
RNA is hypothesized to have been the genetic material of the original.pdfRNA is hypothesized to have been the genetic material of the original.pdf
RNA is hypothesized to have been the genetic material of the original.pdffasttracktreding
 
What is a tissue What are some identifying features of meristematic.pdf
What is a tissue  What are some identifying features of meristematic.pdfWhat is a tissue  What are some identifying features of meristematic.pdf
What is a tissue What are some identifying features of meristematic.pdffasttracktreding
 
You are a systems engineer assigned to a project that is developing .pdf
You are a systems engineer assigned to a project that is developing .pdfYou are a systems engineer assigned to a project that is developing .pdf
You are a systems engineer assigned to a project that is developing .pdffasttracktreding
 
What is the main purpose of a protocol a. Increase network bandwidt.pdf
What is the main purpose of a protocol  a. Increase network bandwidt.pdfWhat is the main purpose of a protocol  a. Increase network bandwidt.pdf
What is the main purpose of a protocol a. Increase network bandwidt.pdffasttracktreding
 
Prove that compactness is a topological property. SolutionSupp.pdf
Prove that compactness is a topological property.  SolutionSupp.pdfProve that compactness is a topological property.  SolutionSupp.pdf
Prove that compactness is a topological property. SolutionSupp.pdffasttracktreding
 

More from fasttracktreding (8)

Which words can be used to describe quantitative research methods (.pdf
Which words can be used to describe quantitative research methods (.pdfWhich words can be used to describe quantitative research methods (.pdf
Which words can be used to describe quantitative research methods (.pdf
 
TRUE OR FALSE when preparing journal entries, the account titles.pdf
TRUE OR FALSE when preparing journal entries, the account titles.pdfTRUE OR FALSE when preparing journal entries, the account titles.pdf
TRUE OR FALSE when preparing journal entries, the account titles.pdf
 
The home and neighborhood environment are critical factors in childr.pdf
The home and neighborhood environment are critical factors in childr.pdfThe home and neighborhood environment are critical factors in childr.pdf
The home and neighborhood environment are critical factors in childr.pdf
 
RNA is hypothesized to have been the genetic material of the original.pdf
RNA is hypothesized to have been the genetic material of the original.pdfRNA is hypothesized to have been the genetic material of the original.pdf
RNA is hypothesized to have been the genetic material of the original.pdf
 
What is a tissue What are some identifying features of meristematic.pdf
What is a tissue  What are some identifying features of meristematic.pdfWhat is a tissue  What are some identifying features of meristematic.pdf
What is a tissue What are some identifying features of meristematic.pdf
 
You are a systems engineer assigned to a project that is developing .pdf
You are a systems engineer assigned to a project that is developing .pdfYou are a systems engineer assigned to a project that is developing .pdf
You are a systems engineer assigned to a project that is developing .pdf
 
What is the main purpose of a protocol a. Increase network bandwidt.pdf
What is the main purpose of a protocol  a. Increase network bandwidt.pdfWhat is the main purpose of a protocol  a. Increase network bandwidt.pdf
What is the main purpose of a protocol a. Increase network bandwidt.pdf
 
Prove that compactness is a topological property. SolutionSupp.pdf
Prove that compactness is a topological property.  SolutionSupp.pdfProve that compactness is a topological property.  SolutionSupp.pdf
Prove that compactness is a topological property. SolutionSupp.pdf
 

Recently uploaded

Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 

Recently uploaded (20)

Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 

Simple array Java code.The “Park-a-lot” parking garage currently o.pdf

  • 1. Simple array Java code. The “Park-a-lot” parking garage currently operates without any computerized system. The management has concerns about inefficiencies of sub-optimal usage of parking space (lost opportunity/profit). Congestion inside the garage is often caused by drivers searching for vacant spots. Currently, the management monitors the garage occupancy by having employees walk around the decks to inspect the occupancy of individual spots. Now you are hired to develop a more advanced system to track and manage occupancy of a parking garage and allow customers to find and reserve available parking places. 1. There are 50 parking spaces in total in this parking lot garage 2. The occupancy state of each parking spot: “available,” “reserved,” or “occupied” 3. The customer should be able to check the parking space availability by specifying the desired date and time interval. If the system responds stating that there are available spots, the customer should be able to make the parking reservation by data and time 4. The customer should be able to modify their existing reservation(s) before the start time of their particular reservation. 5. The customer should be able to extend their current occupancy of a parking space only before their current ending time Solution // importing all required libraries import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; import java.util.*; import java.io.*; /* The CarFrame class is an implementation of the JFrame and also contains the main method. Usage: > java CarFrame Note that the file carData.txt must be in the same directory as all compiled code.
  • 2. */ public class CarFrame extends JFrame { public static JTabbedPane index; public static CarLot myCarLot; public CarFrame() { // setting window properties this.setSize(Toolkit.getDefaultToolkit().getScreenSize()); this.setDefaultCloseOperation(3); this.setTitle("Car Park System"); this.setResizable(false); Color newColor = new Color(0.2f, 0.1f, 0.8f, 0.1f); // creating Car Lot object myCarLot = new CarLot(15, "carData.txt"); // building tabbed panel display index = new JTabbedPane(); index.setBackground(newColor); final JPanel statusTab = Status.startup(); final JPanel addOrRemoveCarTab = AddOrRemoveCar.startup(); // adding tabs to tabbed panel index.addTab("Lot Status", statusTab); index.addTab("Add Or Remove Cars", addOrRemoveCarTab); // setting content pane this.getContentPane().add(index); } public static void main(String[] args) { // initialize frame and set visible CarFrame main = new CarFrame(); main.setVisible(true); } } class CarLot {
  • 3. // class variables private Vector registeredDrivers; private Vector parkingStalls; private String dataFile; private int maxLotSize; // constructor public CarLot(int maxSize, String fileName) { registeredDrivers = new Vector(); parkingStalls = new Vector(); maxLotSize = maxSize; dataFile = fileName; loadData(); } public String getDataFileName() { return dataFile; } public int getMaxSize() { return maxLotSize; } public int carCount() { return parkingStalls.size(); } // Input: license plate number // Output: Stall number in parking lot // Error State: returned String is "" public String findStallLocation(String licenseNum) { String currentStall = ""; String returnVal = ""; for(int i = 0; i < parkingStalls.size(); i++) {
  • 4. currentStall = (String)parkingStalls.elementAt(i); if(licenseNum.equals(currentStall)) { returnVal = Integer.toString(i); break; } } return returnVal; } // Loads data from file (maintain persistence upon close) public int loadData() { // each row in the data file represents a registered car // format: // licensePlateNum|currentlyParked FileReader file; BufferedReader buffer; StringTokenizer tokens; String currentLine = ""; String licensePlate = ""; String currentlyParked = ""; try { file = new FileReader(dataFile); buffer = new BufferedReader(file); // read and parse each line in the file while((currentLine = buffer.readLine()) != null) { int returnVal = 0; tokens = new StringTokenizer(currentLine, "|"); licensePlate = tokens.nextToken(); currentlyParked = tokens.nextToken(); // load all registered drivers registeredDrivers.addElement(licensePlate); // load car into stall if status is "Y"
  • 5. if(currentlyParked.equals("Y")) { if(parkingStalls.size() < maxLotSize) { parkingStalls.addElement(licensePlate); } else { returnVal = -1; } } } } catch(FileNotFoundException f) { return -1; } catch(IOException io) { return -1; } return 0; } // Saves status data upon request to data file public int saveData() { FileWriter writer = null; PrintWriter printer = null; String currentRecord = ""; String licensePlate = ""; String parkedPlates = ""; String currentlyParked = ""; try { writer = new FileWriter(dataFile);
  • 6. printer = new PrintWriter(writer); // build data record by parsing Vectors for(int i = 0; i < registeredDrivers.size(); i++) { licensePlate = (String)registeredDrivers.elementAt(i); currentlyParked = "N"; for(int j = 0; j < parkingStalls.size(); j++) { parkedPlates = (String)parkingStalls.elementAt(j); if(parkedPlates.equals(licensePlate)) { currentlyParked = "Y"; break; } } currentRecord = licensePlate + "|" + currentlyParked; // output record to file printer.println(currentRecord); } // close output streams writer.close(); printer.close(); } catch(IOException io) { return -1; } return 0; } public boolean carEnter(String licenseNum) { String parkedCar = ""; boolean alreadyHere = false; // Check stalls to see if car is already parked
  • 7. for(int i = 0; i < parkingStalls.size(); i++) { parkedCar = (String)parkingStalls.elementAt(i); if(parkedCar.equals(licenseNum)) { alreadyHere = true; } } // car is not already parked if(!alreadyHere) { // space is still available if(!lotFull()) { parkingStalls.addElement(licenseNum); return true; } // space not available else { return false; } } // car already parked in lot else { return false; } } public boolean carExit(String licenseNum) { boolean returnVal = false; //default return value String parkedCar = ""; // searching for car in stalls for(int i = 0; i < parkingStalls.size(); i++)
  • 8. { parkedCar = (String)parkingStalls.elementAt(i); // car found if(parkedCar.equals(licenseNum)) { parkingStalls.removeElementAt(i); returnVal = true; break; } } return returnVal; } public boolean lotFull() { // compare stalls occupied to max lot size if(parkingStalls.size() == maxLotSize) { return true; } else { return false; } } } /* Provides the graphical layout for the Status tab */ class Status { public static JPanel statusTab = new JPanel(); public static JPanel statusScreen1; static JTextField licensePlateField = new JTextField(20); // retrieves Status panel and sets visible static JPanel startup() {
  • 9. statusScreen1 = Status.getStatusScreen1(); statusTab.add(statusScreen1); statusScreen1.setVisible(true); return statusTab; } //defines and retrieves Status panel static JPanel getStatusScreen1() { statusScreen1 = new JPanel(new FlowLayout()); JPanel generalPanel = new JPanel(); generalPanel.setLayout(new BoxLayout(generalPanel, BoxLayout.Y_AXIS)); generalPanel.add(Box.createVerticalStrut(170)); JPanel holderPanel = new JPanel(new BorderLayout()); holderPanel.setLayout(new BoxLayout(holderPanel, BoxLayout.Y_AXIS)); JPanel criteriaPanel = new JPanel(); criteriaPanel.setLayout(new BoxLayout(criteriaPanel, BoxLayout.X_AXIS)); JLabel licensePlateLabel = new JLabel("License Plate Number:"); Font textFont = new Font("SanSerif", Font.PLAIN, 24); Font textFieldFont = new Font("Serif", Font.PLAIN, 20); licensePlateLabel.setFont(textFont); licensePlateField.setFont(textFieldFont); criteriaPanel.add(Box.createHorizontalStrut(40)); criteriaPanel.add(licensePlateLabel); criteriaPanel.add(licensePlateField); criteriaPanel.add(Box.createHorizontalStrut(40)); final JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS)); JButton lotCapacityButton = new JButton("Check Lot Capacity"); JButton saveStateButton = new JButton("Save Lot State"); JButton findStallButton = new JButton("Locate Vehicle"); JButton clearButton = new JButton(" Clear "); lotCapacityButton.setFont(textFont);
  • 10. saveStateButton.setFont(textFont); findStallButton.setFont(textFont); clearButton.setFont(textFont); buttonPanel.add(Box.createHorizontalStrut(10)); buttonPanel.add(lotCapacityButton); buttonPanel.add(saveStateButton); buttonPanel.add(findStallButton); buttonPanel.add(clearButton); holderPanel.add(criteriaPanel); holderPanel.add(Box.createVerticalStrut(30)); holderPanel.add(buttonPanel); generalPanel.add(holderPanel); statusScreen1.add(generalPanel); statusScreen1.add(Box.createHorizontalStrut(150)); // button listener for lot capacity lotCapacityButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Retrieve required information String licensePlate = licensePlateField.getText().trim(); int totalCapacity = CarFrame.myCarLot.getMaxSize(); int currentlyOccupied = CarFrame.myCarLot.carCount(); int freeSpace = totalCapacity - currentlyOccupied; // Print dialog box JOptionPane.showMessageDialog((Component) buttonPanel, "Total Capacity: " + totalCapacity + " Currently Occupied: " + currentlyOccupied + " Free Space: " + freeSpace, "Current Car Lot Statistics", JOptionPane.INFORMATION_MESSAGE); // reset active tab and field data CarFrame.index.setSelectedIndex(0); licensePlateField.setText("");
  • 11. } }); // button listener for save state saveStateButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // perform save operation int result = CarFrame.myCarLot.saveData(); // check if successful and report results if(result == 0) { JOptionPane.showMessageDialog((Component) buttonPanel, "Data for all registered users has been updated in file: " + CarFrame.myCarLot.getDataFileName(), "Data Stored Successfully", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog((Component) buttonPanel, "Data could not be stored!", "Data Extract Failure", JOptionPane.ERROR_MESSAGE); } // reset active tab and field data CarFrame.index.setSelectedIndex(0); licensePlateField.setText(""); } }); // button listener for car location search findStallButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // retrieve input and perform search String licensePlate = licensePlateField.getText().trim(); String stallNumber =
  • 12. CarFrame.myCarLot.findStallLocation(licensePlate); // check operation result and report using dialog boxes if(!stallNumber.equals("")) { JOptionPane.showMessageDialog((Component) buttonPanel, "Location of car #" + licensePlate + ":" + " Stall " + stallNumber, "Car Location Found", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog((Component) buttonPanel, "Location of car #" + licensePlate + ":" + "Could not be found." + " The vehicle is either not registered or not currently parked.", "Car Location Found", JOptionPane.ERROR_MESSAGE); } // reset active tab and field data CarFrame.index.setSelectedIndex(0); licensePlateField.setText(""); } }); // button listener for clear clearButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // reset license plate field licensePlateField.setText(""); } }); return statusScreen1; } }
  • 13. /* Provides the graphical layout for the Add or Remove Car tab */ class AddOrRemoveCar { public static JPanel addOrRemoveCarTab = new JPanel(); public static JPanel addOrRemoveCarScreen1; static JTextField licensePlateField = new JTextField(20); // Retrieves and returns add/remove car panel static JPanel startup() { addOrRemoveCarScreen1 = AddOrRemoveCar.getAddOrRemoveCarScreen1(); addOrRemoveCarTab.add(addOrRemoveCarScreen1); addOrRemoveCarScreen1.setVisible(true); return addOrRemoveCarTab; } // Defines and returns graphical components for screen static JPanel getAddOrRemoveCarScreen1() { addOrRemoveCarScreen1 = new JPanel(new FlowLayout()); JPanel generalPanel = new JPanel(); generalPanel.setLayout(new BoxLayout(generalPanel, BoxLayout.Y_AXIS)); generalPanel.add(Box.createVerticalStrut(170)); JPanel holderPanel = new JPanel(new BorderLayout()); holderPanel.setLayout(new BoxLayout(holderPanel, BoxLayout.X_AXIS)); JPanel criteriaPanel = new JPanel(new FlowLayout()); JLabel licensePlateLabel = new JLabel("License Plate Number:", SwingConstants.RIGHT); Font textFont = new Font("SanSerif", Font.PLAIN, 24); Font textFieldFont = new Font("Serif", Font.PLAIN, 20); licensePlateLabel.setFont(textFont); licensePlateField.setFont(textFieldFont); criteriaPanel.add(licensePlateLabel);
  • 14. criteriaPanel.add(licensePlateField); final JPanel buttonPanel = new JPanel(new FlowLayout()); buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS)); JButton addButton = new JButton("Add Car to Lot"); JButton removeButton = new JButton("Remove Car from Lot"); JButton clearButton = new JButton("Clear Data"); addButton.setFont(textFont); removeButton.setFont(textFont); clearButton.setFont(textFont); buttonPanel.add(Box.createHorizontalStrut(10)); buttonPanel.add(addButton); buttonPanel.add(removeButton); buttonPanel.add(clearButton); holderPanel.add(criteriaPanel); generalPanel.add(holderPanel); holderPanel.add(Box.createVerticalStrut(75)); generalPanel.add(buttonPanel); addOrRemoveCarScreen1.add(generalPanel); addOrRemoveCarScreen1.add(Box.createHorizontalStrut(100)); // button listener for adding car to lot addButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String licensePlate = licensePlateField.getText().trim(); // check validity of input if((licensePlate.length() == 0)) { JOptionPane.showMessageDialog((Component) buttonPanel, "Please fill in the field and try again", "Blank Field", JOptionPane.ERROR_MESSAGE); } else
  • 15. { // perform enter operation boolean result = CarFrame.myCarLot.carEnter(licensePlate); // check outcome and report results if(!result) { JOptionPane.showMessageDialog((Component) buttonPanel, "This license plate is either not registered or is already in the lot. " + "Please try again.", "Invalid Operation", JOptionPane.ERROR_MESSAGE); } else { int another = JOptionPane.showConfirmDialog((Component) buttonPanel, "The car has been added. Add another car to the lot?", "Add Car", JOptionPane.YES_NO_OPTION); // reset input field licensePlateField.setText(""); // change tabs based on user input if(another == JOptionPane.NO_OPTION) { CarFrame.index.setSelectedIndex(0); } } } } }); // button listener for removing car from lot removeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // retrieve input data
  • 16. String licensePlate = licensePlateField.getText().trim(); // check data validity if((licensePlate.length() == 0)) { // invalid JOptionPane.showMessageDialog((Component) buttonPanel, "Please fill in the field and try again", "Blank Field", JOptionPane.ERROR_MESSAGE); } else { // valid // perform exit operation boolean result = CarFrame.myCarLot.carExit(licensePlate); // check outcome and report results if(!result) { JOptionPane.showMessageDialog((Component) buttonPanel, "This license plate is invalid or is already in the lot. Please try again.", "Invalid Operation", JOptionPane.ERROR_MESSAGE); } else { int another = JOptionPane.showConfirmDialog((Component) buttonPanel, "The car has been removed. Remove another car?", "Add Car", JOptionPane.YES_NO_OPTION); licensePlateField.setText(""); if(another == JOptionPane.NO_OPTION) { CarFrame.index.setSelectedIndex(0); } }
  • 17. } } }); // button listener for clear button clearButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // reset text field licensePlateField.setText(""); } }); return addOrRemoveCarScreen1; } }