0% found this document useful (0 votes)
152 views37 pages

Shefali Mahajan Java Final Project

This document contains the code for a Car class with attributes like number of doors, VIN number, maker, model etc. and methods to get/set these attributes, recreate a car object from a string, display car info. It also contains a FileIO class with methods to read/write from files, get file contents as a string, append lines. The classes are part of a final exam project on modeling cars with input/output from files.

Uploaded by

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

Shefali Mahajan Java Final Project

This document contains the code for a Car class with attributes like number of doors, VIN number, maker, model etc. and methods to get/set these attributes, recreate a car object from a string, display car info. It also contains a FileIO class with methods to read/write from files, get file contents as a string, append lines. The classes are part of a final exam project on modeling cars with input/output from files.

Uploaded by

api-298545475
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Programming in Java

Final Exam Project


Cars
Shefali Mahajan

Al Ameerah Khan

Marian Moranchel

Part I

Part II
package COMMON_CARDB;
/**
*
*/
public class Car {

//--------------- Declare attributes


private long numberOfDoors;
private String vinNumber;
private String maker;
private String model;
private String type;
private String engineVolume; // e.g. 3.2 L
private String color;
//--------------- Declare constructors
public Car() {
numberOfDoors = 0;
vinNumber = "";
maker = "";
model = "";
type = "";
engineVolume = "";
color = "";
} // End of default constructor
// Another constructor
// This constructor recreates a car object out of a string of car info
// The string aStrCarData is of CSV format - has been verified: NOT NULL and NOT EMPTY STRING
public Car(String aStrCarData) {
Car aCar = recreateCarFromString(aStrCarData);
numberOfDoors = aCar.getNumberOfDoors();
vinNumber = aCar.getVinNumber();
maker = aCar.getMaker();
model = aCar.getModel();
type = aCar.getType();
engineVolume = aCar.getEngineVolume();
color = aCar.getColor();
} // End of another constructor

//--------------- GET & SET methods


public long getNumberOfDoors() {
return numberOfDoors;
}

public void setNumberOfDoors(long numberOfDoors) {


this.numberOfDoors = numberOfDoors;
}

public String getVinNumber() {


return vinNumber;
}

public void setVinNumber(String vinNumber) {


this.vinNumber = vinNumber;
}

public String getMaker() {


return maker;
}

public void setMaker(String maker) {


this.maker = maker;
}

public String getModel() {


return model;
}

public void setModel(String model) {


this.model = model;
}

public String getType() {


return type;
}

public void setType(String type) {


this.type = type;
}

public String getEngineVolume() {


return engineVolume;
}

public void setEngineVolume(String engineVolume) {


this.engineVolume = engineVolume;
}

public String getColor() {


return color;
}

public void setColor(String color) {


this.color = color;
}
//--------------- Other methods
// This method returns a string that stores all data fields of a car record
// The fields are separated by a comma ','
// The string can be used to insert a car record (a line) into a .CSV file database
// This method overrides the same method of class Object from which all Java classes inherit
@Override
public String toString() {
String carStr = vinNumber
+ "," + maker
+ "," + model
+ "," + type
+ "," + engineVolume
+ "," + Long.toString(numberOfDoors)
+ "," + color;

return (carStr);
} // End of toString

// This method recreate a Car object out of a string of CSV format.


// This string contains all data fields of the car
// After recreating the car, the method returns the object
public static Car recreateCarFromString(String aStrCarData) {
Car aCar = new Car();
if (aStrCarData.isEmpty()) {

return (null);
}
String[] result = aStrCarData.split(",");
aCar.setVinNumber(result[0]);
aCar.setMaker(result[1]);
aCar.setModel(result[2]);
aCar.setType(result[3]);
aCar.setEngineVolume(result[4]);
aCar.setNumberOfDoors(Long.parseLong(result[5]));
aCar.setColor(result[6]);
return (aCar);
}

public void displayCarInfo() {


System.out.println(toString());
} // End of displayCarInfo

} // End of class Car

Part II (FileIO)
package COMMON_CARDB;
/**
*
*/
import java.io.*;

public class FileIO {


//------------- Declare attributes
private static final int maxNumLines = 1000; // a constant
private int numLines;
private String[] strLinesArray;

//------------- Declare constructors


// Default constructor
public FileIO() {
// Initialize with 0
numLines = 0;
// For simplicity, allocate space for maxNumLine lines,
// adequate for normal files
strLinesArray = new String[maxNumLines];
// Initialize all the elements with empty string
java.util.Arrays.fill(strLinesArray, "");
} // End of default constructor FiLEIO

// Another constructor
public FileIO(File aFile) throws FileNotFoundException, IOException {
// Initialize with 0
// numLines = 0;
// For simplicity, allocate space for maxNumLine lines,
// adequate for normal files
strLinesArray = new String[maxNumLines];
// Initialize all the elements with empty string
java.util.Arrays.fill(strLinesArray, "");
try {

numLines = readLinesFromFile(aFile);
}
catch (IOException ex) {
ex.printStackTrace();
}
}

//------------- GET & SET methods


public static int getMaxNumLines() {
return(maxNumLines);
}

public int getNumLines() {


return(numLines);
}
public void setNumLines(int aNumLines) {
numLines = aNumLines;
}
public String[] getStrLinesArray() {
return (strLinesArray);
}

public void setStrLinesArray(String[] aStrArray) {


for (int i = 0; i < aStrArray.length; i++) {
// Copy element by element from aStrArray to strLinesArray
strLinesArray[i] = aStrArray[i];
}
}

//------------- File IO methods


public static void checkAndThrowExceptionsForInputFile (File aFile) throws FileNotFoundException,
IOException {
if (aFile == null) { throw new IllegalArgumentException("File should not be null.");}
if (!aFile.exists()) { throw new FileNotFoundException ("File does not exist: " + aFile);}
if (!aFile.isFile()) { throw new IllegalArgumentException("Should not be a directory: " + aFile);
}
if (!aFile.canRead()) { throw new IllegalArgumentException("File cannot be read: " + aFile); }
} // End of checkAndThrowExceptionsForInputFile

public static void checkAndThrowExceptionsForOutputFile (File aFile) throws FileNotFoundException,


IOException {
if (aFile == null) { throw new IllegalArgumentException("File should not be null.");}
if (!aFile.exists()) { throw new FileNotFoundException ("File does not exist: " + aFile);}
if (!aFile.isFile()) { throw new IllegalArgumentException("Should not be a directory: " + aFile);
}
if (!aFile.canWrite()) { throw new IllegalArgumentException("File cannot be written: " + aFile);
}
} // End of checkAndThrowExceptionsForOutputFile

/*
Comments:
* This method changes the contents of text file in its entirety, overwriting any existing text.
* This style of implementation throws all exceptions to the caller.
* This method uses the following classes: File, Writer, FileWriter, BufferedWriter
* This method uses FileWriter --> using the default coding scheme of the system
*/
public void setContents(File aFile, String aContents) throws FileNotFoundException, IOException {
checkAndThrowExceptionsForOutputFile(aFile);
//use buffering
Writer output = new BufferedWriter(new FileWriter(aFile));
try {
//FileWriter always assumes default encoding is OK!
output.write( aContents );
}
finally {
output.close();
}
} // End of setContents
/*
Comments:
* This method fetches the content of the whole file and returns the content as a String
* The String contains "lineSeparator"
* This style of implementation throws all exceptions to the caller.
*
* This method uses the following classes: File, StringBuilder, BufferedReader, FileReader
* This method uses readLine()
* --> returns the content of a line MINUS the newline
* --> returns null only for the END of the stream
* --> returns an empty String if two newlines appear in a row

*/
public String getContents(File aFile) {
// Create an object "contents" of class StringBuilder
StringBuilder contents = new StringBuilder();
try { // try #1
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
BufferedReader input = new BufferedReader (new FileReader(aFile));

try { // try #2
String line = null;

//not declared within while loop

// readLine is a bit quirky :


// it returns the content of a line MINUS the newline.
// it returns null only for the END of the stream.
// it returns an empty String if two newlines appear in a row.
while (( line = input.readLine()) != null) {
contents.append(line);
contents.append(System.getProperty("line.separator"));
} // End of while
} // End of try #2
finally { // try #2
input.close();
}
} // End of try #1
catch (IOException ex){ // try #1
ex.printStackTrace();
}
return contents.toString();
} // End of getContents()
/*
Comments:
* This method appends one line to an existing file
* This style of implementation throws all exceptions to the caller.
* This method uses the following classes: File, FileWriter, BufferedWriter
* This method uses FileWriter --> using the default coding scheme of the system

/*
public void appendOneLineToFile(File aFile, String aStrLine) throws FileNotFoundException,
IOException {
checkAndThrowExceptionsForOutputFile(aFile);
// Use constructor" FileWriter(File aFile, boolean append)
// boolean append: TRUE --> appending is allowed for this file
try { // try #1
FileWriter aFileWriter = new FileWriter (aFile, true);
BufferedWriter output = new BufferedWriter(aFileWriter);
try {
//FileWriter always assumes default encoding is OK!
// Append the input String to the file as a new line
output.append ( aStrLine );
output.newLine();
}
finally {
output.close();
}
} // End of try #1
catch (IOException ex){ // try #1
ex.printStackTrace();
}
} // End of appendOnelineToFile

/*
Comments:
* This method read one line from an existing file and returns a String
* This style of implementation throws all exceptions to the caller.
* This method uses the following classes: File, FileReader, BufferedReader

*/
public int readLinesFromFile (File aFile) throws FileNotFoundException, IOException {
// Reset numLines to 0 to be sure
numLines = 0;
checkAndThrowExceptionsForInputFile(aFile);

// Use constructor" FileWriter(File aFile, boolean append)


// boolean append: TRUE --> appending is allowed for this file
try { // try #1
FileReader aFileReader = new FileReader (aFile);
BufferedReader input = new BufferedReader (aFileReader);
String line = null;

//not declared within while loop

try {
// readLine is a bit quirky :
// it returns the content of a line MINUS the newline.
// it returns null only for the END of the stream.
// it returns an empty String if two newlines appear in a row.
line = input.readLine();
while ( line != null) {
// numLines can be used as array index before being incremented
// MUST allocate new space for array element
// to be sure that it refers to a String physically different from "line"
strLinesArray[numLines] = new String(line);
// Increment by 1 to indicate the correct number of lines
numLines++;
// Read another line if existing
line = input.readLine();
} // End of while
} // End of try #2
finally {
input.close();
}
} // End of try #1
catch (IOException ex){ // try #1
ex.printStackTrace();
}

return (numLines);
} // End of readLinesFromFile

public void displayFileContent() {


if (numLines > 0) {

for (int j = 0; j < numLines; j++) {


System.out.println (strLinesArray[j]);
}
}
else {
// File is empty
System.out.println ("File is empty: no line");
}
} // End of displayFileContent

} // End of class FileIO

Part III
package CREATE_CARDB;
/**
*
*/
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
import java.io.*;
import COMMON_CARDB.Car;
import COMMON_CARDB.FileIO;
import org.apache.commons.lang3.*;
public class CreateCarDb {
private JFrame frmCreateCarDatabase;
private JLabel lblEnterVIN;
private JTextField textFieldVIN;
private JLabel lblEnterMaker;
private JTextField textFieldMaker;
private JLabel lblEnterModel;
private JTextField textFieldModel;
private JLabel lblEnterType;
private JTextField textFieldType;
private JLabel lblEnterEngineVolume;
private JTextField textFieldEngineVolume;
private JLabel lblEnterNumberOfDoors;
private JTextField textFieldNumberOfDoors;
private JLabel lblEnterColor;
private JTextField textFieldColor;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {

try {
CreateCarDb window = new CreateCarDb();
window.frmCreateCarDatabase.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public CreateCarDb() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmCreateCarDatabase = new JFrame();
frmCreateCarDatabase.getContentPane().setFont(new Font("Tahoma", Font.PLAIN, 11));
frmCreateCarDatabase.setTitle("Create Car Database");
frmCreateCarDatabase.setBounds(100, 100, 472, 604);
frmCreateCarDatabase.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmCreateCarDatabase.getContentPane().setLayout(null);
lblEnterVIN = new JLabel("Enter VIN:");
lblEnterVIN.setFont(new Font("Times New Roman", Font.PLAIN, 16));
lblEnterVIN.setBounds(52, 50, 101, 20);
frmCreateCarDatabase.getContentPane().add(lblEnterVIN);
textFieldVIN = new JTextField();
textFieldVIN.setBounds(220, 54, 166, 20);
frmCreateCarDatabase.getContentPane().add(textFieldVIN);
textFieldVIN.setColumns(10);
lblEnterMaker = new JLabel("Enter Maker:");
lblEnterMaker.setFont(new Font("Times New Roman", Font.PLAIN, 16));
lblEnterMaker.setBounds(52, 110, 101, 20);
frmCreateCarDatabase.getContentPane().add(lblEnterMaker);
textFieldMaker = new JTextField();
textFieldMaker.setBounds(220, 114, 166, 20);
frmCreateCarDatabase.getContentPane().add(textFieldMaker);
textFieldMaker.setColumns(10);
lblEnterModel = new JLabel("Enter Model:");
lblEnterModel.setFont(new Font("Times New Roman", Font.PLAIN, 16));
lblEnterModel.setBounds(52, 170, 101, 20);
frmCreateCarDatabase.getContentPane().add(lblEnterModel);

textFieldModel = new JTextField();


textFieldModel.setBounds(220, 174, 166, 20);
frmCreateCarDatabase.getContentPane().add(textFieldModel);
textFieldModel.setColumns(10);
lblEnterType = new JLabel("Enter Type:");
lblEnterType.setFont(new Font("Times New Roman", Font.PLAIN, 16));
lblEnterType.setBounds(52, 230, 101, 20);
frmCreateCarDatabase.getContentPane().add(lblEnterType);
textFieldType = new JTextField();
textFieldType.setBounds(220, 234, 166, 20);
frmCreateCarDatabase.getContentPane().add(textFieldType);
textFieldType.setColumns(10);
lblEnterEngineVolume = new JLabel("Enter Engine Volume:");
lblEnterEngineVolume.setFont(new Font("Times New Roman", Font.PLAIN, 16));
lblEnterEngineVolume.setBounds(52, 290, 166, 20);
frmCreateCarDatabase.getContentPane().add(lblEnterEngineVolume);
textFieldEngineVolume = new JTextField();
textFieldEngineVolume.setBounds(220, 294, 166, 20);
frmCreateCarDatabase.getContentPane().add(textFieldEngineVolume);
textFieldEngineVolume.setColumns(10);
lblEnterNumberOfDoors = new JLabel("Enter Number of Doors:");
lblEnterNumberOfDoors.setFont(new Font("Times New Roman", Font.PLAIN, 16));
lblEnterNumberOfDoors.setBounds(52, 350, 166, 20);
frmCreateCarDatabase.getContentPane().add(lblEnterNumberOfDoors);
textFieldNumberOfDoors = new JTextField();
textFieldNumberOfDoors.setBounds(220, 354, 166, 20);
frmCreateCarDatabase.getContentPane().add(textFieldNumberOfDoors);
textFieldNumberOfDoors.setColumns(10);
lblEnterColor = new JLabel("Enter Color:");
lblEnterColor.setFont(new Font("Times New Roman", Font.PLAIN, 16));
lblEnterColor.setBounds(52, 410, 101, 20);
frmCreateCarDatabase.getContentPane().add(lblEnterColor);
textFieldColor = new JTextField();
textFieldColor.setBounds(220, 414, 166, 20);
frmCreateCarDatabase.getContentPane().add(textFieldColor);
textFieldColor.setColumns(10);

JButton btnSubmit = new JButton("Submit");


btnSubmit.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {

try {
btnSubmit_CLICK();
}
catch (Exception e) {
System.out.println(e.toString());
}
}
});
btnSubmit.setFont(new Font("Times New Roman", Font.PLAIN, 24));
btnSubmit.setBounds(158, 476, 151, 28);
frmCreateCarDatabase.getContentPane().add(btnSubmit);
JLabel lblAlertMessage = new JLabel("");
lblAlertMessage.setForeground(Color.RED);
lblAlertMessage.setFont(new Font("Times New Roman", Font.BOLD, 16));
lblAlertMessage.setBounds(52, 528, 362, 27);
frmCreateCarDatabase.getContentPane().add(lblAlertMessage);
} // End of initialize

private void btnSubmit_CLICK() {


//-------------- First, validate all the text fields
// If any problem, a dialog warning pops up to stop the program
boolean isValidated = validateTextFields();
if (! isValidated) return;

//-------------- All the text fields have been validated


FileIO fileIOHandler = new FileIO();
// Declare output file database: carDatabase.txt
//File outputFile = new File("/Users/salikshariff/Documents/javaproject/carDatabase.txt");
File outputFile = new File("resources/carDatabase.txt");
Car aCar = new Car();
aCar.setVinNumber(textFieldVIN.getText());
aCar.setMaker(textFieldMaker.getText());
aCar.setModel(textFieldModel.getText());
aCar.setType(textFieldType.getText());
aCar.setEngineVolume(textFieldEngineVolume.getText());
aCar.setNumberOfDoors(Long.parseLong(textFieldNumberOfDoors.getText()));
aCar.setColor(textFieldColor.getText());
// Get the string of car data
String strCarInfo = aCar.toString();

try {
// Write the string to the Car database file
// by adding a line to the file
fileIOHandler.appendOneLineToFile(outputFile, strCarInfo);
}
catch (IOException ex){
ex.printStackTrace();
}
// At this point, already successfully inserting a new car record into the database
JOptionPane.showMessageDialog(frmCreateCarDatabase, "The new car record has been
successfully inserted into the database.");
// After successfully inserting a new car record to the database
// refresh all the text fields to prepare for the next record
textFieldVIN.setText("");
textFieldMaker.setText("");
textFieldModel.setText("");
textFieldType.setText("");
textFieldEngineVolume.setText("");
textFieldNumberOfDoors.setText("");
textFieldColor.setText("");
} // End of btnSubmit_CLICK

/****************************
* Name: validateTextFields
* Parameters: None
* Return: boolean
* --> TRUE: all the text fields are successfully validate
* --> FALSE: at least one text field has failed the validation
* Description:
* --> This method verify to be sure each text field contains valid data:
* --> Valid data: not null, not zero-size data, not empty String, not filled only with blank space
* --> For VIN: valid data must also be 16 Letters long Alpha Numeric
* --> For Number of Doors: valid data must also be only Numeric
*
****************************/
private boolean validateTextFields() {
boolean isValidated = true;
//----------- Validate VIN text field
try{
Validate.notBlank(textFieldVIN.getText());
}catch(Exception e){
JOptionPane.showMessageDialog(frmCreateCarDatabase, "All the text fields must have
valid values - VIN cannot be blank !!!.");
textFieldVIN.requestFocusInWindow(); // make it ready to enter the value
textFieldVIN.selectAll(); // select all text in the text field to delete it or to replace it

isValidated = false;
}
if (! isValidated) return (isValidated);
// For VIN, also need to verify the entered Length
if(textFieldVIN.getText().length()!=16){
JOptionPane.showMessageDialog(frmCreateCarDatabase, "VIN must be a 16 Letters
AlphaNumeric Value.");
textFieldVIN.requestFocusInWindow(); // make it ready to enter the value
textFieldVIN.selectAll(); // select all text in the text field to delete it or to replace it
isValidated = false;
}
if (! isValidated) return (isValidated);
//----------- Validate Maker text field
try{
Validate.notBlank(textFieldMaker.getText());
}catch(Exception e){
JOptionPane.showMessageDialog(frmCreateCarDatabase, "All the text fields must have
valid values - Maker cannot be blank !!!.");
textFieldMaker.requestFocusInWindow(); // make it ready to enter the value
textFieldMaker.selectAll(); // select all text in the text field to delete it or to replace it
isValidated = false;
}
if (! isValidated) return (isValidated);
//----------- Validate Model text field
try{
Validate.notBlank(textFieldModel.getText());
}catch(Exception e){
JOptionPane.showMessageDialog(frmCreateCarDatabase, "All the text fields must have
valid values - Model cannot be blank !!!.");
textFieldModel.requestFocusInWindow(); // make it ready to enter the value
textFieldModel.selectAll(); // select all text in the text field to delete it or to replace it
isValidated = false;
}
if (! isValidated) return (isValidated);
//----------- Validate Type text field
try{
Validate.notBlank(textFieldType.getText());
}catch(Exception e){
JOptionPane.showMessageDialog(frmCreateCarDatabase, "All the text fields must have
valid values - Type cannot be blank !!!.");
textFieldType.requestFocusInWindow(); // make it ready to enter the value

textFieldType.selectAll(); // select all text in the text field to delete it or to replace it


isValidated = false;
}
if (! isValidated) return (isValidated);
//----------- Validate Engine Volume text field
try{
Validate.notBlank(textFieldEngineVolume.getText());
}catch(Exception e){
JOptionPane.showMessageDialog(frmCreateCarDatabase, "All the text fields must have
valid values - Engine Volume cannot be blank !!!.");
textFieldEngineVolume.requestFocusInWindow(); // make it ready to enter the value
textFieldEngineVolume.selectAll(); // select all text in the text field to delete it or to
replace it
isValidated = false;
}
if (! isValidated) return (isValidated);
//----------- Validate Number of Doors text field
try{
Validate.notBlank(textFieldNumberOfDoors.getText());
}catch(Exception e){
JOptionPane.showMessageDialog(frmCreateCarDatabase, "All the text fields must have
valid values - Number of Doors cannot be blank !!!.");
textFieldNumberOfDoors.requestFocusInWindow(); // make it ready to enter the value
textFieldNumberOfDoors.selectAll(); // select all text in the text field to delete it or to
replace it
isValidated = false;
}
if (! isValidated) return (isValidated);
// For ISBN, also need to verify the entered value is a valid numeric
try{
long tempLong = Long.parseLong(textFieldNumberOfDoors.getText());
}catch(Exception e){
JOptionPane.showMessageDialog(frmCreateCarDatabase, "Number of Doors must have
a Numeric Value.");
textFieldNumberOfDoors.requestFocusInWindow(); // make it ready to enter the value
textFieldNumberOfDoors.selectAll(); // select all text in the text field to delete it or to
replace it
isValidated = false;
}
if (! isValidated) return (isValidated);
//----------- Validate Color text field
try{

Validate.notBlank(textFieldColor.getText());
}catch(Exception e){
JOptionPane.showMessageDialog(frmCreateCarDatabase, "All the text fields must have
valid values - Color cannot be blank !!!.");
textFieldColor.requestFocusInWindow(); // make it ready to enter the value
textFieldColor.selectAll(); // select all text in the text field to delete it or to replace it
isValidated = false;
}
return (isValidated);
} // validateTextFields

} // End of class CreateCar

Part IV
package SEARCH_CARDB;
/**
*
*/
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.border.BevelBorder;
import javax.swing.JTextArea;
import java.io.*;
import COMMON_CARDB.Car;
import COMMON_CARDB.FileIO;
import org.apache.commons.lang3.Validate;
public class SearchCarDb {
private JFrame frmSearchCarDatabase;
private JComboBox comboBoxAttribute;
private JTextField textFieldSearchValue;
private JTextArea textAreaSearchResults;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SearchCarDb window = new SearchCarDb();
window.frmSearchCarDatabase.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});

}
/**
* Create the application.
*/
public SearchCarDb() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmSearchCarDatabase = new JFrame();
frmSearchCarDatabase.setTitle("Search Car Database");
frmSearchCarDatabase.setBounds(100, 100, 674, 552);
frmSearchCarDatabase.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmSearchCarDatabase.getContentPane().setLayout(null);
JLabel lblSearchAttribute = new JLabel("Select attribute to search:");
lblSearchAttribute.setFont(new Font("Times New Roman", Font.PLAIN, 20));
lblSearchAttribute.setBounds(60, 60, 220, 24);
frmSearchCarDatabase.getContentPane().add(lblSearchAttribute);
String [] carAttributeList = {"ALL", "VIN", "Maker", "Model", "Type", "Engine Volume",
"Number of Doors", "Color"};
comboBoxAttribute = new JComboBox(carAttributeList);
comboBoxAttribute.setFont(new Font("Times New Roman", Font.PLAIN, 18));
comboBoxAttribute.setBounds(290, 65, 185, 20);
frmSearchCarDatabase.getContentPane().add(comboBoxAttribute);
JLabel lblEnterSearchValue = new JLabel("Enter value to search:");
lblEnterSearchValue.setFont(new Font("Times New Roman", Font.PLAIN, 20));
lblEnterSearchValue.setBounds(60, 140, 220, 24);
frmSearchCarDatabase.getContentPane().add(lblEnterSearchValue);
textFieldSearchValue = new JTextField();
textFieldSearchValue.setFont(new Font("Times New Roman", Font.PLAIN, 16));
textFieldSearchValue.setBounds(290, 145, 185, 20);
frmSearchCarDatabase.getContentPane().add(textFieldSearchValue);
textFieldSearchValue.setColumns(10);
JButton btnSubmit = new JButton("Submit");
btnSubmit.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
try {
btnSubmit_CLICK();
}
catch (Exception e) {
System.out.println(e.toString());

}
} // End of mouseClicked
});
btnSubmit.setFont(new Font("Times New Roman", Font.PLAIN, 24));
btnSubmit.setBounds(186, 213, 170, 29);
frmSearchCarDatabase.getContentPane().add(btnSubmit);
JScrollPane scrollPaneSearchResults = new JScrollPane();
scrollPaneSearchResults.setViewportBorder(new BevelBorder(BevelBorder.RAISED, null, null,
null, null));
scrollPaneSearchResults.setBounds(38, 288, 570, 167);
frmSearchCarDatabase.getContentPane().add(scrollPaneSearchResults);
JLabel lblCarSearchResults = new JLabel("Car Search Results");
lblCarSearchResults.setFont(new Font("Times New Roman", Font.PLAIN, 24));
scrollPaneSearchResults.setColumnHeaderView(lblCarSearchResults);
textAreaSearchResults = new JTextArea();
textAreaSearchResults.setFont(new Font("Times New Roman", Font.PLAIN, 16));
scrollPaneSearchResults.setViewportView(textAreaSearchResults);
} // End of initialize

private void btnSubmit_CLICK() {


// Refresh the text area of search results --> make it blank
textAreaSearchResults.setText("");
//-------------- First, validate all the text fields
// If any problem, a dialog warning pops up to stop the program
boolean isValidated = validateTextFields();
if (! isValidated) return;

//-------------- All the text fields have been validated


FileIO fileIOHandler = new FileIO();
// Declare the target file database: carDatabase.txt
//File fileDB = new File("/Users/salikshariff/Documents/javaproject/carDatabase.txt");
File fileDB = new File("resources/carDatabase.txt");
int numCarsInDb = 0; // number of cars in DB
int numFoundCars = 0; // number of found cars
String[] carsDbArray; // Array of all car records in DB --> array of String
Car [] foundCarsArray = new Car[FileIO.getMaxNumLines()]; // Array of found cars --> array
of cars
try {

// Read all the records from car file database


numCarsInDb = fileIOHandler.readLinesFromFile(fileDB);
carsDbArray = fileIOHandler.getStrLinesArray();
// Get the selected item from ComboBox
String strSelectedAttribute = (String) comboBoxAttribute.getSelectedItem();
// Get the search value
String strSearchValue = textFieldSearchValue.getText();
// Invoke searchCars()
numFoundCars = searchCars (numCarsInDb, carsDbArray, foundCarsArray,
strSelectedAttribute, strSearchValue);
// If no matched car is found, display warning
if (numFoundCars == 0) {
textAreaSearchResults.append("No matched cars is found in the database. \n");
}
}
catch (IOException ex){
ex.printStackTrace();
}

} // End of btnSubmit_CLICK

/****************************
* Name: validateTextFields
* Parameters: None
* Return: boolean
* --> TRUE: The search value text field is successfully validate
* --> FALSE: The text field has failed the validation
* Description:
* --> This method verify to be sure the search value text field contains valid data:
* --> Valid data: not null, not zero-size data, not empty String, not filled only with blank space
* --> If VIN is selected as search attribute: valid data must also be 16 Letter AlphanNumeric
* --> If Number of Doors is selected as search attribute: valid data must also be number
*
****************************/
private boolean validateTextFields() {
boolean isValidated = true;
//----------- Validate the text field of search value
// Need to validate for every search attribute except for "ALL"
if( ! comboBoxAttribute.getSelectedItem().equals("ALL")) {

try{
Validate.notBlank(textFieldSearchValue.getText());
}catch(Exception e){
JOptionPane.showMessageDialog(frmSearchCarDatabase, "The text field of
search value must have valid values - Cannot be blank !!!.");
textFieldSearchValue.requestFocusInWindow(); // make it ready to enter the
value
textFieldSearchValue.selectAll(); // select all text in the text field to delete it or to
replace it
isValidated = false;
}
}
// If any problem, stop the program
if (! isValidated) return (isValidated);
// For Number of Doors, also need to verify the entered value is a valid numeric
if(comboBoxAttribute.getSelectedItem().equals("Number of Doors")){
try{
Long.parseLong(textFieldSearchValue.getText());
}catch(Exception e){
JOptionPane.showMessageDialog(frmSearchCarDatabase, "Number of Doors must have
a Numeric Value.");
textFieldSearchValue.requestFocusInWindow(); // make it ready to enter the
value
textFieldSearchValue.selectAll(); // select all text in the text field to delete it ot to
replace it
isValidated = false;
}
}
// If any problem, stop the program
if (! isValidated) return (isValidated);
// For VIN, also need to verify the length is 16
if(comboBoxAttribute.getSelectedItem().equals("VIN")){
if(textFieldSearchValue.getText().length()!=16){
JOptionPane.showMessageDialog(frmSearchCarDatabase, "VIN must be 16 Letter
long.");
textFieldSearchValue.requestFocusInWindow(); // make it ready to enter the
value
textFieldSearchValue.selectAll(); // select all text in the text field to delete it ot to
replace it
isValidated = false;
}
}
return (isValidated);
} // validateTextFields
/*******************
* Name: searchCars
* Parameters:

* --> numCars: number of cars in the carArray


* --> carsArray: array of strings, each string is a car record (in DB) of CSV format
* --> foundCarsArray: array of class Car elements that are found in the database
* --> aStrSearchAttr: a String that represents an attribute that is used to search
* --> aStrSearchValue: a String that represents the value of the attribute used to search
* Return
* --> This method returns an array of Car objects - cars that are found in the database
* Description:
* This method performs a search for cars whose attribute has the value that is
* matched with cars in the car array
********************/
private int searchCars(int numCars,
String[] carsArray,
Car[] foundCarsArray,
String aStrSearchAttr,
String aStrSearchValue) {
int numFoundCars = 0;
if (aStrSearchAttr.equals("ALL")) {
// ALL is used to search for cars
numFoundCars = searchCarByAll(numCars, carsArray, foundCarsArray);
} // End of if (ALL)
if (aStrSearchAttr.equals("VIN")) {
// VIN is used to search for cars
numFoundCars = searchCarByVIN(numCars, aStrSearchValue, carsArray,
foundCarsArray);
} // End of if (VIN)
if (aStrSearchAttr.equals("Maker")) {
// Maker is used to search for cars
numFoundCars = searchCarByMaker(numCars, aStrSearchValue, carsArray,
foundCarsArray);

} // End of if (Maker)

if (aStrSearchAttr.equals("Model")) {
// Model is used to search for cars
numFoundCars = searchCarByModel(numCars, aStrSearchValue, carsArray,
foundCarsArray);
} // End of if (Model)

if (aStrSearchAttr.equals("Type")) {
// Type is used to search for cars
numFoundCars = searchCarByType(numCars, aStrSearchValue, carsArray,
foundCarsArray);
} // End of if (Type)

if (aStrSearchAttr.equals("Engine Volume")) {
// Engine Volume is used to search for cars
numFoundCars = searchCarByEngineVolume(numCars, aStrSearchValue, carsArray,
foundCarsArray);
} // End of if (Engine Volume)

if (aStrSearchAttr.equals("Number of Doors")) {
// Number of Doors is used to search for cars
numFoundCars = searchCarByNumberOfDoors(numCars, aStrSearchValue, carsArray,
foundCarsArray);
} // End of if (Number of Doors)
if (aStrSearchAttr.equals("Color")) {
// Color is used to search for cars
numFoundCars = searchCarByColor(numCars, aStrSearchValue, carsArray,
foundCarsArray);
} // End of if (Color)

return (numFoundCars);

} // End of searchCars

private int searchCarByAll(int numCars, String[] carsArray, Car[] foundCarsArray) {


int numFoundCars = 0;
String aStrCarRecord = "";
for (int i = 0; i < numCars; i++) {
aStrCarRecord = carsArray[i];

// a car is found --> add car into found-car array


Car aFoundCar = new Car (aStrCarRecord);
foundCarsArray[numFoundCars] = aFoundCar;
// Increment numFoundCars to indicate one more car is found
numFoundCars++;
} // End of for (scan car array)
// Write car record of each found car into the text area (car search results)
for (int j = 0; j < numFoundCars; j++) {
// Append a car record into the search results text area
textAreaSearchResults.append((foundCarsArray[j]).toString() + "\n");
}

return (numFoundCars);

} // End of searchCarByAll

private int searchCarByVIN(int numCars, String strVIN, String[] carsArray, Car[] foundCarsArray) {
Car aCar;
String strDbCarVIN = ""; // VIN of car in database
int numFoundCars = 0;
String aStrCarRecord = "";
for (int i = 0; i < numCars; i++) {
aStrCarRecord = carsArray[i];
aCar = Car.recreateCarFromString(aStrCarRecord);
// First convert string value to long
strDbCarVIN = aCar.getVinNumber(); // Get VIN of the car in db
if (strDbCarVIN.equals(strVIN)){
// a car is found --> add car into found-car array
Car aFoundCar = new Car (aStrCarRecord);
foundCarsArray[numFoundCars] = aFoundCar;
// Increment numFoundCars to indicate one more car is found
numFoundCars++;
}
} // End of for (scan car array)
// Write car record of each found car into the text area (car search results)

for (int j = 0; j < numFoundCars; j++) {


// Append a car record into the search results text area
textAreaSearchResults.append((foundCarsArray[j]).toString() + "\n");
}

return (numFoundCars);

} // End of searchCarByVIN

private int searchCarByMaker(int numCars, String strMaker, String[] carsArray, Car[] foundCarsArray)
{
Car aCar;
String strDbCarMaker = ""; // Maker of car in database
int numFoundCars = 0;
String aStrCarRecord = "";
for (int i = 0; i < numCars; i++) {
aStrCarRecord = carsArray[i];
aCar = Car.recreateCarFromString(aStrCarRecord);
strDbCarMaker = aCar.getMaker(); // Get maker of the car in db
if (strDbCarMaker.equals(strMaker)){
// a car is found --> add car into found-car array
Car aFoundCar = new Car (aStrCarRecord);
foundCarsArray[numFoundCars] = aFoundCar;
// Increment numFoundCars to indicate one more car is found
numFoundCars++;
}
} // End of for (scan car array)

// Write car record of each found car into the text area (car search results)
for (int j = 0; j < numFoundCars; j++) {
// Append a car record into the search results text area
textAreaSearchResults.append((foundCarsArray[j]).toString() + "\n");
}

return (numFoundCars);

} // End of searchCarByMaker

private int searchCarByModel(int numCars, String strModel, String[] carsArray, Car[] foundCarsArray)
{
Car aCar;
String strDbCarModel = ""; // Model of car in database
int numFoundCars = 0;
String aStrCarRecord = "";
for (int i = 0; i < numCars; i++) {
aStrCarRecord = carsArray[i];
aCar = Car.recreateCarFromString(aStrCarRecord);
strDbCarModel = aCar.getModel(); // Get model of the car in db
if ((strDbCarModel.equals(strModel))){
// a car is found --> add car into found-car array
Car aFoundCar = new Car (aStrCarRecord);
foundCarsArray[numFoundCars] = aFoundCar;
// Increment numFoundCars to indicate one more car is found
numFoundCars++;
}
} // End of for (scan car array)
// Write car record of each found car into the text area (car search results)
for (int j = 0; j < numFoundCars; j++) {
// Append a car record into the search results text area
textAreaSearchResults.append((foundCarsArray[j]).toString() + "\n");
}
return (numFoundCars);

} // End of searchCarByModel

private int searchCarByType(int numCars, String strType, String[] carsArray, Car[] foundCarsArray) {
Car aCar;
String strDbCarType = ""; // Type of car in database
int numFoundCars = 0;
String aStrCarRecord = "";

for (int i = 0; i < numCars; i++) {


aStrCarRecord = carsArray[i];
aCar = Car.recreateCarFromString(aStrCarRecord);
strDbCarType = aCar.getType(); // Get type of the car in db
if ((strDbCarType.equals(strType))){
// a car is found --> add car into found-car array
Car aFoundCar = new Car (aStrCarRecord);
foundCarsArray[numFoundCars] = aFoundCar;
// Increment numFoundCars to indicate one more car is found
numFoundCars++;
}
} // End of for (scan car array)
// Write car record of each found car into the text area (car search results)
for (int j = 0; j < numFoundCars; j++) {
// Append a car record into the search results text area
textAreaSearchResults.append((foundCarsArray[j]).toString() + "\n");
}
return (numFoundCars);

} // End of searchCarByType
private int searchCarByEngineVolume(int numCars, String strEngineVolume, String[] carsArray, Car[]
foundCarsArray) {
Car aCar;
String strDbCarEngineVolume = ""; // Engine Volume of car in database
int numFoundCars = 0;
String aStrCarRecord = "";
for (int i = 0; i < numCars; i++) {
aStrCarRecord = carsArray[i];
aCar = Car.recreateCarFromString(aStrCarRecord);
strDbCarEngineVolume = aCar.getEngineVolume(); // Get Engine Volume of the car in
db
if ((strDbCarEngineVolume.equals(strEngineVolume))){
// a car is found --> add car into found-car array
Car aFoundCar = new Car (aStrCarRecord);

foundCarsArray[numFoundCars] = aFoundCar;
// Increment numFoundCars to indicate one more car is found
numFoundCars++;
}
} // End of for (scan car array)

// Write car record of each found car into the text area (car search results)
for (int j = 0; j < numFoundCars; j++) {
// Append a car record into the search results text area
textAreaSearchResults.append((foundCarsArray[j]).toString() + "\n");
}
return (numFoundCars);

} // End of searchCarByEngineVolume

private int searchCarByNumberOfDoors(int numCars, String strNumberOfDoors, String[] carsArray,


Car[] foundCarsArray) {
Car aCar;
int numFoundCars = 0;
String aStrCarRecord = "";
for (int i = 0; i < numCars; i++) {
aStrCarRecord = carsArray[i];
aCar = Car.recreateCarFromString(aStrCarRecord);
// First convert string value to long
long numberOfDoors = Long.parseLong(strNumberOfDoors);
if (numberOfDoors == aCar.getNumberOfDoors()){
// a car is found --> add car into found-car array
Car aFoundCar = new Car (aStrCarRecord);
foundCarsArray[numFoundCars] = aFoundCar;
// Increment numFoundCars to indicate one more car is found
numFoundCars++;
}
} // End of for (scan car array)
// Write car record of each found car into the text area (car search results)

for (int j = 0; j < numFoundCars; j++) {


// Append a car record into the search results text area
textAreaSearchResults.append((foundCarsArray[j]).toString() + "\n");
}

return (numFoundCars);

} // End of searchCarByNumberOfDoors

private int searchCarByColor(int numCars, String strColor, String[] carsArray, Car[] foundCarsArray) {
Car aCar;
String strDbCarColor = ""; // Color of car in database
int numFoundCars = 0;
String aStrCarRecord = "";
for (int i = 0; i < numCars; i++) {
aStrCarRecord = carsArray[i];
aCar = Car.recreateCarFromString(aStrCarRecord);
strDbCarColor = aCar.getColor(); // Get Color of the car in db
if ((strDbCarColor.equals(strColor))){
// a car is found --> add car into found-car array
Car aFoundCar = new Car (aStrCarRecord);
foundCarsArray[numFoundCars] = aFoundCar;
// Increment numFoundCars to indicate one more car is found
numFoundCars++;
}
} // End of for (scan car array)

// Write car record of each found car into the text area (car search results)
for (int j = 0; j < numFoundCars; j++) {
// Append a car record into the search results text area
textAreaSearchResults.append((foundCarsArray[j]).toString() + "\n");
}
return (numFoundCars);

} // End of searchCarByColor
} // End of class SearchCarDb

Car Database:
1. BJH1234567890ABC,Honda,Accord,Sedan,3.2L,4,Blue
2. ADC1234567890XYZ,BMW,M5,Sedan,5.0L,4,Black
3. BNB1237868903RTY,BMW,M3,Coupe,5.0L,2,White
4. ACFSD456TGHUE432,Lamborghini,Huracan ,Coupe,4.8,2,Orange
5. W33D4577890324AT,Honda,Civic,Coupe,2.5L,2,White
6. BO0912345689QAS3,Toyota,Tundra,Truck,3.5L,4,Black
7. SJNFDAE11U128611,Nissan,Altima,Sedan,2.5L,4,Blue
8. SJNFCAJ10U130474,Ford,Mustang GT,Coupe,5.0,2,White
9. BRD123990872OKLI,Jaguar,S Type,Sedan,4.0L,4,Maroon
10. NHT678543210OK78,Toyota,Camry,Sedan,2.5L,4,Black
11. KMLN767899023GBV,Lexus,ES,Sedan,3.5L,4,Silver
12. MJHBVC67GHF65423,Lexus,IS,Sedan,2.5L,4,Green
13. UYG67230KKL98756,BMW,3 Series,Coupe,3.5L,2,White
14. KJMN98760098HNBV,Chevrolet,Impala,Sedan,3.0L,4,Silver
15. YT7865EDSCBW3300,Infiniti,G37,Coupe,3.5L,2,Black
16. 998BVNBTGFV67800,Mercedes,C300,Sedan,3.0L,4,Black

MIS4310 Spring 2015


Programming in Java
Final Project Contribution Evaluation
My Group: Group # 2 (Cars)
My team members:
(1)

You: Shefali Mahajan

(2)

Al Ameerah Khan

(3)

Marian Moranchel

I evaluate other team members contribution to the project as follows


On scale of 10
10 is the highest
Team member #2: 10
Team member #3: 10

Important Notes:
This page must be attached to the hard copy of the solution as the last page.

You might also like