I'll use this page to put up some code from my school days. If anyone finds any use for any of my projects (I see all you plagiarizers out there....and I'm not judging ;) ) It would make my day. If there are any suggestions as to what's good/bad about my style or choices, feedback is also VERY welcome!
SO, I've decided to post some of my projects at school here, and here's the first one, which I did a few months ago. Nothing special, it took me a couple days. It's a java GUI for a bookstore's inventory. It's not exactly a point of sale app, and not exactly useful, but it's an idea of what a 1st year can do.... enjoy!
Just copy all these code snippets into separate text files with the same name as
the headings, compile them, and then run "java Bookstore", and you should see a GUI pop up.
Bookstore.java
/**
Assignment 4
@author MasudKhan
Class containing the main method for running the
Bookstore inventory application.
*/
/**
main driver class for Bookstore Inventory application.
*/
public class Bookstore
{
// main method
public static void main(String[] args)
{
BookstoreMainFrame gui = new BookstoreMainFrame();
gui.setVisible(true);
}
}
BookstoreMainFrame.java
/**
Assignment 4
@author MasudKhan
This class creates the main frame object that the user
will interact with the most.
*/
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.InputMismatchException;
import java.util.Scanner;
/**
Class for the main frame of the GUI.
*/
public class BookstoreMainFrame extends JFrame implements ActionListener
{
public static final int NUMBER_OF_CHARS = 15;
public static final int WIDTH = 600;
public static final int HEIGHT = 400;
// the object that holds the ArrayList with the BookRecords in it
private BookRecordKeeper recordListObject;
// 2 main panels for main frame
private JPanel topPanel;
private JPanel bottomPanel;
// a reference to use for the txt area in the bottom panel
private JTextArea printer;
private JTextField searchField; // reference for search field
private JComboBox searchCriteriaBox; // reference for search criteria
private File bufferFile; // file to be used to save/open/save as... records
private JMenuItem bufferItem; // used to allow Save menu item
/**
Constructor: adds all main components to the 2 main panels
and toolbar, and then adds the panels to the frame.
*/
public BookstoreMainFrame()
{
// set basic frame traits
super("Bookstore Inventory");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// helper method to create top panel
createTopPanel();
// helper method to create bottom panel
createBottomPanel();
// helper method to create menu bar
createMenuBar();
// initialize object holding the BookRecord ArrayList
File recoveredSave = new File("BookRecords.txt");
if(recoveredSave.exists()) // load save from text at start-up
{
try
{
recordListObject =
readRecordListFromText(recoveredSave);
printer.append("\nBook Record List loaded!");
}
catch(FileNotFoundException e)
{
printer.append("\nNo records saved.");
recordListObject = new BookRecordKeeper();
}
catch(EOFException e)
{
printer.append("\nError loading records.");
recordListObject = new BookRecordKeeper();
}
catch(Exception e)
{
printer.append("\nUnknown error loading records.");
recordListObject = new BookRecordKeeper();
}
}
else
{
// in case there is no save recovery file
recordListObject = new BookRecordKeeper();
}
}
/**
Postcondition: creates top panel and adds it to main frame.
*/
private void createTopPanel()
{
// set panel color
topPanel = new JPanel();
// same JButton reference is used for each button to save memory
JButton bufferButton;
bufferButton = new JButton("Add Book");
bufferButton.addActionListener(new AddBookListener());
topPanel.add(bufferButton);
bufferButton = new JButton("Remove Book");
bufferButton.addActionListener(new RemoveBookListener());
topPanel.add(bufferButton);
bufferButton = new JButton("New Record");
bufferButton.addActionListener(new AddBookRecordListener());
topPanel.add(bufferButton);
bufferButton = new JButton("Delete Record");
bufferButton.addActionListener(new RemoveBookRecordListener());
topPanel.add(bufferButton);
add(topPanel, BorderLayout.NORTH); // adds panel to main frame
}
/**
Postcondition: creates bottom panel and adds it to main frame.
*/
private void createBottomPanel()
{
bottomPanel = new JPanel();
bottomPanel.setLayout(new BorderLayout());
// aesthetic value only. adds border to bottom panel
bottomPanel.add(new JPanel(), BorderLayout.NORTH);
bottomPanel.add(new JPanel(), BorderLayout.EAST);
bottomPanel.add(new JPanel(), BorderLayout.SOUTH);
// create Search button and ISBNSearchField with label
JPanel southWestPanel = new JPanel();
southWestPanel.setLayout(new GridLayout(10, 1));
// create search label and field
JButton searchButton = new JButton("Search");
searchButton.setBackground(Color.LIGHT_GRAY); // Search button stands out
searchButton.addActionListener(this);
searchField = new JTextField(10);
// create JComboBox for search criteria
String[] criteriaBoxOptions = {"Title", "Category", "Author",
"Publisher", "Year of Publication", "ISBN", "Quantity",
"Quantity Sold", "Inventory Cost", "Selling Price"};
searchCriteriaBox = new JComboBox(criteriaBoxOptions);
// add search label, search field and search criteria combo box
southWestPanel.add(new JPanel());
southWestPanel.add(searchButton);
southWestPanel.add(new JPanel());
southWestPanel.add(searchCriteriaBox);
southWestPanel.add(searchField);
southWestPanel.add(new JPanel());
southWestPanel.add(new JPanel());
southWestPanel.add(new JPanel());
southWestPanel.add(new JPanel());
// create button to show all records in textArea
JButton showAllRecordsButton = new JButton("Show All Records");
showAllRecordsButton.addActionListener(this);
southWestPanel.add(showAllRecordsButton);
bottomPanel.add(southWestPanel, BorderLayout.WEST);
// create and add text area with scroll bar to bottom panel
printer = new JTextArea(10, 40);
printer.setEditable(false);
printer.setLineWrap(true);
printer.setText("\tWelcome to Bookstore Inventory Application\n");
// ScrollBar addition
JScrollPane printerScroll = new JScrollPane(printer);
printerScroll.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
printerScroll.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
bottomPanel.add(printerScroll, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.CENTER); // add bottom panel to main frame
}
/**
Postcondition: creates menu bar and adds it to frame.
*/
private void createMenuBar()
{
// create File menu
JMenu mainMenu = new JMenu("File");
bufferItem = new JMenuItem("Save to Text File");
bufferItem.addActionListener(new TextIOListener());
mainMenu.add(bufferItem);
bufferItem = new JMenuItem("Open from Text File");
bufferItem.addActionListener(new TextIOListener());
mainMenu.add(bufferItem);
bufferItem = new JMenuItem("Open .ser File(advanced)");
bufferItem.addActionListener(this);
mainMenu.add(bufferItem);
bufferItem = new JMenuItem("Save As .ser(advanced)...");
bufferItem.addActionListener(this);
mainMenu.add(bufferItem);
// put this item last so that it's accessible outside constructor
bufferItem = new JMenuItem("Save .ser");
bufferItem.addActionListener(this);
if(bufferFile == null)// if recovered save file not found
{
bufferItem.setEnabled(false);
}
mainMenu.add(bufferItem);
JMenuBar bar = new JMenuBar();
bar.add(mainMenu);
// create Sale menu
mainMenu = new JMenu("Sale");
JMenuItem bufferItem2 = new JMenuItem("Book Sold");
bufferItem2.addActionListener(new BookSoldListener());
mainMenu.add(bufferItem2);
bufferItem2 = new JMenuItem("Save Transaction Summary");
bufferItem2.addActionListener(this);
mainMenu.add(bufferItem2);
bar.add(mainMenu);
setJMenuBar(bar);
}
/**
Precondition: if search is clicked, then searchField must have input.
Postcondition: Checks which component was clicked(search,
Open from Text File, Save to Text File, Open .ser File(advanced),
Save As .ser File(advanced)..., Save .ser) and calls associated helper method.
@param evt the event being fired
*/
public void actionPerformed(ActionEvent evt)
{
if(evt.getActionCommand().equals("Search"))
{
if(searchCriteriaBox.getSelectedItem().equals("Title"))
{
searchTitle(); //helper method
}
else if(searchCriteriaBox.getSelectedItem().equals("Category"))
{
searchCategory(); //helper method
}
else if(searchCriteriaBox.getSelectedItem().equals("Author"))
{
searchAuthor(); //helper method
}
else if(searchCriteriaBox.getSelectedItem().equals("Publisher"))
{
searchPublisher(); //helper method
}
else if(searchCriteriaBox.getSelectedItem().equals("Year of Publication"))
{
try
{
searchYearOfPublication(); //helper method
}
catch(Exception e)
{
printer.setText("\tInvalid Year of Publication. Try again.");
}
}
else if(searchCriteriaBox.getSelectedItem().equals("ISBN"))
{
searchISBN(); //helper method
}
else if(searchCriteriaBox.getSelectedItem().equals("Quantity"))
{
try
{
searchQuantity(); //helper method
}
catch(Exception e)
{
printer.setText("\tInvalid Quantity. Try again.");
}
}
else if(searchCriteriaBox.getSelectedItem().equals("Quantity Sold"))
{
try
{
searchQuantitySold(); //helper method
}
catch(Exception e)
{
printer.setText("\tInvalid Quantity Sold. Try again.");
}
}
else if(searchCriteriaBox.getSelectedItem().equals("Inventory Cost"))
{
try
{
searchInventoryCost(); //helper method
}
catch(Exception e)
{
printer.setText("\tInvalid Inventory Cost. Try again.");
}
}
else if(searchCriteriaBox.getSelectedItem().equals("Selling Price"))
{
try
{
searchSellingPrice(); //helper method
}
catch(Exception e)
{
printer.setText("\tInvalid Selling Price. Try again.");
}
}
}
else if(evt.getActionCommand().equals("Open .ser File(advanced)"))
{
try
{
open(); // helper method
}
catch(Exception e)
{
printer.setText("\tCould not open file.");
}
}
else if(evt.getActionCommand().equals("Save .ser"))
{
try
{
ObjectOutputStream saveAsOutputStream =
new ObjectOutputStream(new FileOutputStream(bufferFile));
saveAsOutputStream.writeObject(recordListObject);
saveAsOutputStream.close();
printer.setText("\tAll records saved.");
}
catch(Exception e)
{
printer.setText("\tError saving file. Try again.");
}
}
else if(evt.getActionCommand().equals("Save As .ser(advanced)..."))
{
try
{
saveAs(); // helper method
}
catch(Exception e)
{
printer.setText("\tError saving file. Try again.");
}
}
else if(evt.getActionCommand().equals("Save Transaction Summary"))
{
printTransactionsToTextFile();
}
else
{
showAllRecords(); // helper method
}
}
/**
Precondition: user must choose a valid file with A BookRecordKeeper
object as it's only contents.
Postcondition: sets the BookRecordKeeper object to the
object read from the chosen file.
@throws IOException, ClassNotFoundException
*/
private void open() throws IOException, ClassNotFoundException
{
JFileChooser chooser = new JFileChooser();
chooser.addChoosableFileFilter(
new FileNameExtensionFilter("Serial files", "ser"));
if(chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
{
bufferFile = chooser.getSelectedFile(); // quick save now possible
ObjectInputStream openInputStream =
new ObjectInputStream(new FileInputStream(bufferFile));
recordListObject = (BookRecordKeeper)openInputStream.readObject();
openInputStream.close();
showAllRecords();
bufferItem.setEnabled(true); // allow save menu item
printer.append("\n\nRECORDS LOADED.");
}
}
/**
Precondition: user must choose a valid text file in the same format as
written by the program when saving records to a text file.
Postcondition: sets the BookRecordKeeper object to a new object that contains
the loaded information from the chosen text file.
*/
private void openRecordListFromText()
{
JFileChooser chooser = new JFileChooser();
chooser.addChoosableFileFilter(
new FileNameExtensionFilter("Text files", "txt"));
if(chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
{
try
{
recordListObject =
readRecordListFromText(chooser.getSelectedFile());
showAllRecords();
printer.append("\n\nRECORDS LOADED.");
}
catch(FileNotFoundException e)
{
printer.setText("\nNo records saved.");
recordListObject = new BookRecordKeeper();
}
catch(EOFException e)
{
printer.setText("\nError loading records.");
recordListObject = new BookRecordKeeper();
}
catch(Exception e)
{
printer.setText("\nThe loaded file is corrupt.\n");
printer.append("No records loaded.");
recordListObject = new BookRecordKeeper();
}
}
}
/**
Postcondition: saves file as name specified at location specified.
@throws IOException
*/
private void saveAs() throws IOException
{
JFileChooser chooser = new JFileChooser();
if(chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
{
bufferFile = new File("BookstoreSAVE.ser"); // quick save now possible
ObjectOutputStream saveAsOutputStream =
new ObjectOutputStream(new FileOutputStream(bufferFile));
saveAsOutputStream.writeObject(recordListObject);
saveAsOutputStream.close();
bufferItem.setEnabled(true); // allow save menu item
printer.setText("\tAll records saved.");
}
}
/**
Postcondition: saves all records to a text file in list form.
*/
public void saveRecordListToText()
{
PrintWriter outputStream = null;
try
{
outputStream =
new PrintWriter(new FileOutputStream("BookRecords.txt"));
for(int i = 0; i < recordListObject.size(); i++)
{
outputStream.println(recordListObject.get(i));
}
outputStream.close();
printer.setText("\tRecords saved to BookRecords.txt");
}
catch(FileNotFoundException e)
{
printer.setText("\tCould not open file to save records.\n");
}
}
/**
Postcondition: prints a transaction summary to a separate text file.
*/
public void printTransactionsToTextFile()
{
double grossProfit = 0.0;
PrintWriter outputStream = null;
try
{
outputStream =
new PrintWriter(new FileOutputStream("Transaction Summary.txt"));
for(int i = 0; i < recordListObject.size(); i++)
{
outputStream.println("Title: " +
recordListObject.get(i).getTitle());
outputStream.println("ISBN: " +
recordListObject.get(i).getISBN());
outputStream.println("Quantity sold: " +
recordListObject.get(i).getQuantitySold());
outputStream.println("Selling price: $" +
recordListObject.get(i).getSellingPrice());
outputStream.println("Inventory Cost: $" +
recordListObject.get(i).getInventoryCost());
grossProfit += (recordListObject.get(i).getQuantitySold() *
recordListObject.get(i).getSellingPrice());
outputStream.println();
}
outputStream.println("\tGross Profit: $" + grossProfit + "\n");
outputStream.println();
outputStream.close();
printer.setText("Transaction summary saved to Transaction Summary.txt.");
}
catch(FileNotFoundException e)
{
printer.setText("\tCould not open file to save transaction summary.\n");
}
}
/**
Precondition: file named BookRecords.txt must be already saved in same file as
the executable, and it must be in same format as what is printed to a text file
by the method saveRecordListToText.
Postcondition: loads records from text file BookRecords.txt.
@param recordFile the file to be read
@return an object storing all the loaded BookRecord objects
@throws EOFException, FileNotFoundException, Exception
*/
public BookRecordKeeper readRecordListFromText(File recordFile)
throws EOFException, FileNotFoundException, Exception
{
Scanner scanFile;
BookRecordKeeper recordKeeperObject = new BookRecordKeeper();
BookRecord tempRecord;
String tempAttribute;
scanFile = new Scanner(new FileInputStream(recordFile));
while(scanFile.hasNext())
{
tempRecord = new BookRecord();
tempAttribute = scanFile.nextLine();
tempAttribute =
tempAttribute.substring(tempAttribute.indexOf(": ") + 2);
tempRecord.setTitle(tempAttribute);
tempAttribute = scanFile.nextLine();
tempAttribute =
tempAttribute.substring(tempAttribute.indexOf(": ") + 2);
tempRecord.setCategory(tempAttribute);
tempAttribute = scanFile.nextLine();
tempAttribute =
tempAttribute.substring(tempAttribute.indexOf(": ") + 2);
tempRecord.setAuthor(tempAttribute);
tempAttribute = scanFile.nextLine();
tempAttribute =
tempAttribute.substring(tempAttribute.indexOf(": ") + 2);
tempRecord.setPublisher(tempAttribute);
tempAttribute = scanFile.nextLine();
tempAttribute =
tempAttribute.substring(tempAttribute.indexOf(": ") + 2);
tempRecord.setYearOfPublication(Integer.parseInt(tempAttribute));
tempAttribute = scanFile.nextLine();
tempAttribute =
tempAttribute.substring(tempAttribute.indexOf(": ") + 2);
tempRecord.setISBN(tempAttribute);
tempAttribute = scanFile.nextLine();
tempAttribute =
tempAttribute.substring(tempAttribute.indexOf(": ") + 2);
tempRecord.setQuantity(Integer.parseInt(tempAttribute));
tempAttribute = scanFile.nextLine();
tempAttribute =
tempAttribute.substring(tempAttribute.indexOf(": ") + 2);
tempRecord.setQuantitySold(Integer.parseInt(tempAttribute));
tempAttribute = scanFile.nextLine();
tempAttribute =
tempAttribute.substring(tempAttribute.indexOf(": ") + 2);
tempRecord.setInventoryCost(Double.parseDouble(tempAttribute.substring(1)));
tempAttribute = scanFile.nextLine();
tempAttribute =
tempAttribute.substring(tempAttribute.indexOf(": ") + 2);
tempRecord.setSellingPrice(Double.parseDouble(tempAttribute.substring(1)));
recordKeeperObject.add(tempRecord);
scanFile.nextLine(); // to skip potential profit line
if(scanFile.hasNext())
{ // to skip empty line
scanFile.nextLine();
}
}
scanFile.close();
return recordKeeperObject;
}
/**
Postcondition: prints all records that match the search and a
count of how many matches were found. Not case-sensitive.
*/
private void searchTitle()
{
String searchTitle = searchField.getText().toLowerCase();
String compareTitle;
int matchCount = 0;
printer.setText(""); // to reset the text area
for(int i = 0; i < recordListObject.size(); i++) // checks all records
{
compareTitle = recordListObject.get(i).getTitle().toLowerCase();
if(searchTitle.equals(compareTitle))
{
printer.append(recordListObject.get(i) + "\n");
matchCount++;
}
}
// print how many matches
printer.append("\n\t\t" + matchCount + " match(es) found.");
}
/**
Postcondition: prints all records that match the search and a
count of how many matches were found. Not case-sensitive.
*/
private void searchCategory()
{
String searchCategory = searchField.getText().toLowerCase();
String compareCategory;
int matchCount = 0;
printer.setText(""); // to reset the text area
for(int i = 0; i < recordListObject.size(); i++) // checks all records
{
compareCategory =
recordListObject.get(i).getCategory().toLowerCase();
if(searchCategory.equals(compareCategory))
{
printer.append(recordListObject.get(i) + "\n");
matchCount++;
}
}
// print how many matches
printer.append("\n\t\t" + matchCount + " match(es) found.");
}
/**
Postcondition: prints all records that match the search and a
count of how many matches were found. Not case-sensitive.
*/
private void searchAuthor()
{
String searchAuthor = searchField.getText().toLowerCase();
String compareAuthor;
int matchCount = 0;
printer.setText(""); // to reset the text area
for(int i = 0; i < recordListObject.size(); i++) // checks all records
{
compareAuthor =
recordListObject.get(i).getAuthor().toLowerCase();
if(searchAuthor.equals(compareAuthor))
{
printer.append(recordListObject.get(i) + "\n");
matchCount++;
}
}
// print how many matches
printer.append("\n\t\t" + matchCount + " match(es) found.");
}
/**
Postcondition: prints all records that match the search and a
count of how many matches were found. Not case-sensitive.
*/
private void searchPublisher()
{
String searchPublisher = searchField.getText().toLowerCase();
String comparePublisher;
int matchCount = 0;
printer.setText(""); // to reset the text area
for(int i = 0; i < recordListObject.size(); i++) // checks all records
{
comparePublisher =
recordListObject.get(i).getPublisher().toLowerCase();
if(searchPublisher.equals(comparePublisher))
{
printer.append(recordListObject.get(i) + "\n");
matchCount++;
}
}
// print how many matches
printer.append("\n\t\t" + matchCount + " match(es) found.");
}
/**
Precondition: value in search field must be an integer.
Postcondition: prints all records that match the search and a
count of how many matches were found.
@throws Exception
*/
private void searchYearOfPublication() throws Exception
{
int searchYearOfPublication = Integer.parseInt(searchField.getText());
int matchCount = 0;
printer.setText(""); // to reset the text area
for(int i = 0; i < recordListObject.size(); i++) // checks all records
{
if(searchYearOfPublication == recordListObject.get(i).getYearOfPublication())
{
printer.append(recordListObject.get(i) + "\n");
matchCount++;
}
}
// print how many matches
printer.append("\n\t\t" + matchCount + " match(es) found.");
}
/**
Precondition: value in search field must be an integer.
Postcondition: prints all records that match the search and a
count of how many matches were found.
*/
private void searchISBN()
{
String searchISBN = searchField.getText().toLowerCase();
String compareISBN;
int matchCount = 0;
printer.setText(""); // to reset the text area
for(int i = 0; i < recordListObject.size(); i++) // checks all records
{
compareISBN =
recordListObject.get(i).getISBN();
if(searchISBN.equals(compareISBN))
{
printer.append(recordListObject.get(i) + "\n");
matchCount++;
}
}
// print how many matches
printer.append("\n\t\t" + matchCount + " match(es) found.");
}
/**
Precondition: value in search field must be an integer.
Postcondition: prints all records that match the search and a
count of how many matches were found.
@throws Exception
*/
private void searchQuantity() throws Exception
{
int searchQuantity = Integer.parseInt(searchField.getText());
int matchCount = 0;
printer.setText(""); // to reset the text area
for(int i = 0; i < recordListObject.size(); i++) // checks all records
{
if(searchQuantity == recordListObject.get(i).getQuantity())
{
printer.append(recordListObject.get(i) + "\n");
matchCount++;
}
}
// print how many matches
printer.append("\n\t\t" + matchCount + " match(es) found.");
}
/**
Precondition: value in search field must be an integer.
Postcondition: prints all records that match the search and a
count of how many matches were found.
@throws Exception
*/
private void searchQuantitySold() throws Exception
{
int searchQuantitySold = Integer.parseInt(searchField.getText());
int matchCount = 0;
printer.setText(""); // to reset the text area
for(int i = 0; i < recordListObject.size(); i++) // checks all records
{
if(searchQuantitySold == recordListObject.get(i).getQuantitySold())
{
printer.append(recordListObject.get(i) + "\n");
matchCount++;
}
}
// print how many matches
printer.append("\n\t\t" + matchCount + " match(es) found.");
}
/**
Precondition: value in search field must be an integer or decimal.
Postcondition: prints all records that match the search and a
count of how many matches were found. Truncates any decimal values,
and just compares integer parts.
@throws Exception
*/
private void searchInventoryCost() throws Exception
{
int searchInventoryCost = (int)Double.parseDouble(searchField.getText());
int matchCount = 0;
printer.setText(""); // to reset the text area
for(int i = 0; i < recordListObject.size(); i++) // checks all records
{
if(searchInventoryCost == (int)recordListObject.get(i).getInventoryCost())
{
printer.append(recordListObject.get(i) + "\n");
matchCount++;
}
}
// print how many matches
printer.append("\n\t\t" + matchCount + " match(es) found.");
}
/**
Precondition: value in search field must be an integer or decimal.
Postcondition: prints all records that match the search and a
count of how many matches were found. Truncates any decimal values,
and just compares integer parts.
@throws Exception
*/
private void searchSellingPrice() throws Exception
{
int searchSellingPrice = (int)Double.parseDouble(searchField.getText());
int matchCount = 0;
printer.setText(""); // to reset the text area
for(int i = 0; i < recordListObject.size(); i++) // checks all records
{
// ignores decimal for accuracy
if(searchSellingPrice == (int)recordListObject.get(i).getSellingPrice())
{
printer.append(recordListObject.get(i) + "\n");
matchCount++;
}
}
// print how many matches
printer.append("\n\t\t" + matchCount + " match(es) found.");
}
/**
Postcondition: prints all BookRecord objects to the text area.,
and then prints the total potential profit for all of them.
*/
private void showAllRecords()
{
printer.setText(""); // to clear text area
double totalPotentialProfit = 0;
int i;
for(i = 0; i < recordListObject.size(); i++)
{
printer.append(recordListObject.get(i) + "\n");
totalPotentialProfit +=
recordListObject.get(i).getPotentialProfit();
}
if(i == 0) // if ArrayList in BookRecordKeeper object is empty
{
printer.setText("NO BOOK RECORDS AVAILABLE\n\n");
}
// print total potential profit
printer.append("\tTotal potential profit: $" + totalPotentialProfit);
}
/**
Listener inner class for Add Book button.
*/
private class AddBookListener extends JFrame implements ActionListener
{
private JTextField ISBNField;
private JTextField quantityField;
/**
Constructor: creates frame with 2 labels, 2 text fields and button.
*/
public AddBookListener()
{
super("Add Book");
setSize(300, 120);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLayout(new GridLayout(2, 2));
setResizable(false);
// create labels, textboxes and OK button
JLabel ISBNPromptLabel = new JLabel("Enter ISBN:(integer)");
ISBNField = new JTextField(NUMBER_OF_CHARS);
JLabel quantityPromptLabel = new JLabel("Enter quantity:(integer)");
quantityField = new JTextField(NUMBER_OF_CHARS);
JButton OKButton = new JButton("OK");
OKButton.addActionListener(this);
// create 2 panels
JPanel top = new JPanel();
top.setLayout(new GridLayout(2, 2));
JPanel bottom = new JPanel();
// add labels/textboxes/panels to panels and panels to frame
top.add(ISBNPromptLabel);
top.add(ISBNField);
top.add(quantityPromptLabel);
top.add(quantityField);
bottom.add(OKButton);
add(top);
add(bottom);
}
/**
Precondition: ISBN and quantity fields must be valid integers.
Postcondition: adds given quantity from specified BookRecord object.
@param evt the event that was fired by the GUI
*/
public void actionPerformed(ActionEvent evt)
{
setVisible(true);
if(evt.getActionCommand().equals("OK")) // makes frame reusable
{
try
{ // assign all values to local variables
int quantityGain = Integer.parseInt(quantityField.getText());
String theISBN = ISBNField.getText();
int indexOfISBN = recordListObject.getIndexOfISBN(theISBN);
int quantityBefore =
recordListObject.get(indexOfISBN).getQuantity();
recordListObject.get(indexOfISBN).setQuantity(
quantityBefore + quantityGain); // sets value
// print the changes made and dispose frame
printer.setText(recordListObject.get(indexOfISBN).toString());
printer.append("\n\t\tBook(s) added.");
dispose();
}
catch(IndexOutOfBoundsException e)
{
JFrame exceptionFrame = new JFrame("ISBN not found.");
exceptionFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
exceptionFrame.setSize(300, 100);
JLabel exceptionLabel =
new JLabel("ISBN number not found.");
exceptionFrame.add(exceptionLabel);
exceptionFrame.setVisible(true);
}
catch(Exception e)
{
JFrame exceptionFrame = new JFrame("Error changing value");
exceptionFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
exceptionFrame.setSize(300, 100);
JLabel exceptionLabel =
new JLabel("Positive integer values only please.");
exceptionFrame.add(exceptionLabel);
exceptionFrame.setVisible(true);
}
finally
{
ISBNField.setText("");
quantityField.setText("");
}
}
}
}
/**
Listener inner class for remove book button.
*/
private class RemoveBookListener extends JFrame implements ActionListener
{
private JTextField ISBNField;
private JTextField quantityField;
/**
Constructor: creates frame with 2 labels, 2 text fields and button.
*/
public RemoveBookListener()
{
super("Remove Book");
setSize(300, 120);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLayout(new GridLayout(2, 2));
setResizable(false);
// create labels, textboxes and OK button
JLabel ISBNPromptLabel = new JLabel("Enter ISBN(integer):");
ISBNField = new JTextField(NUMBER_OF_CHARS);
JLabel quantityPromptLabel =
new JLabel("Enter quantity(integer):");
quantityField = new JTextField(NUMBER_OF_CHARS);
JButton OKButton = new JButton("OK");
OKButton.addActionListener(this);
// create 2 panels
JPanel top = new JPanel();
top.setLayout(new GridLayout(2, 2));
JPanel bottom = new JPanel();
// add labels/textboxes/panels to panels and panels to frame
top.add(ISBNPromptLabel);
top.add(ISBNField);
top.add(quantityPromptLabel);
top.add(quantityField);
bottom.add(OKButton);
add(top);
add(bottom);
}
/**
Precondition: ISBN and quantity fields must be valid integers.
Postcondition: subtracts given quantity from specified book Record object.
@param evt the event being fired.
*/
public void actionPerformed(ActionEvent evt)
{
setVisible(true);
if(evt.getActionCommand().equals("OK")) // makes frame reusable
{
try
{ // assign values to local variables
int quantityLoss = Integer.parseInt(quantityField.getText());
String theISBN = ISBNField.getText();
int indexOfISBN = recordListObject.getIndexOfISBN(theISBN);
int quantityBefore =
recordListObject.get(indexOfISBN).getQuantity();
recordListObject.get(indexOfISBN).setQuantity(
quantityBefore - quantityLoss); // set value
// print changes and dispose frame
printer.setText(recordListObject.get(indexOfISBN).toString());
printer.append("\n\t\tBook(s) removed.");
dispose();
}
catch(IndexOutOfBoundsException e)
{
JFrame exceptionFrame = new JFrame("ISBN not found.");
exceptionFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
exceptionFrame.setSize(300, 100);
JLabel exceptionLabel =
new JLabel("ISBN number not found.");
exceptionFrame.add(exceptionLabel);
exceptionFrame.setVisible(true);
}
catch(Exception e)
{
JFrame exceptionFrame = new JFrame("Error removing books");
exceptionFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
exceptionFrame.setSize(300, 100);
JLabel exceptionLabel =
new JLabel("Unable to remove books.");
exceptionFrame.add(exceptionLabel);
exceptionFrame.setVisible(true);
}
finally
{
ISBNField.setText("");
quantityField.setText("");
}
}
}
}
/**
Inner class for Book Sold Button.
*/
private class BookSoldListener extends JFrame implements ActionListener
{
private JTextField ISBNField;
private JTextField quantitySoldField;
/**
Constructor: creates frame with 2 fields, 2 labels and OK button
*/
public BookSoldListener()
{
super("Book Sold");
setSize(360, 120);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLayout(new GridLayout(2, 2));
setResizable(false);
// create labels, textboxes and OK button
JLabel ISBNPromptLabel = new JLabel("Enter ISBN(integer):");
ISBNField = new JTextField(NUMBER_OF_CHARS);
JLabel quantityPromptLabel =
new JLabel("Enter quantity Sold(integer):");
quantitySoldField = new JTextField(NUMBER_OF_CHARS);
JButton OKButton = new JButton("OK");
OKButton.addActionListener(this);
// create 2 panels
JPanel top = new JPanel();
top.setLayout(new GridLayout(2, 2));
JPanel bottom = new JPanel();
// add labels/textboxes/panels to panels and panels to frame
top.add(ISBNPromptLabel);
top.add(ISBNField);
top.add(quantityPromptLabel);
top.add(quantitySoldField);
bottom.add(OKButton);
add(top);
add(bottom);
}
/**
Precondition: ISBN and quantity fields must be valid integers.
Postcondition: subtracts given quantity from specified book Record object,
and adds the same quantity to the number sold.
@param evt the event being fired.
*/
public void actionPerformed(ActionEvent evt)
{
setVisible(true);
if(evt.getActionCommand().equals("OK")) // makes frame reusable
{
try
{ // assign values to local variables
int quantityLoss = Integer.parseInt(quantitySoldField.getText());
String theISBN = ISBNField.getText();
int indexOfISBN = recordListObject.getIndexOfISBN(theISBN);
int quantityBefore =
recordListObject.get(indexOfISBN).getQuantity();
int quantitySoldBefore =
recordListObject.get(indexOfISBN).getQuantitySold();
recordListObject.get(indexOfISBN).setQuantity(
quantityBefore - quantityLoss); // set value
recordListObject.get(indexOfISBN).setQuantitySold(
quantitySoldBefore + quantityLoss); // set sold value
// print changes and dispose frame
printer.setText(recordListObject.get(indexOfISBN).toString());
printer.append("\n\t\tSale(s) updated, Book(s) removed.");
dispose();
}
catch(IndexOutOfBoundsException e)
{
JFrame exceptionFrame = new JFrame("ISBN not found.");
exceptionFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
exceptionFrame.setSize(300, 100);
JLabel exceptionLabel =
new JLabel("ISBN number not found.");
exceptionFrame.add(exceptionLabel);
exceptionFrame.setVisible(true);
}
catch(Exception e)
{
JFrame exceptionFrame = new JFrame("Error removing books");
exceptionFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
exceptionFrame.setSize(300, 100);
JLabel exceptionLabel =
new JLabel("Unable to remove books.");
exceptionFrame.add(exceptionLabel);
exceptionFrame.setVisible(true);
}
}
}
}
/**
Inner class for Add Book Record button.
*/
private class AddBookRecordListener extends JFrame implements ActionListener
{
// instance variables that will be used
JTextField titleField;
JComboBox categoryBox;
JTextField authorField;
JTextField publisherField;
JTextField yearOfPublicationField;
JTextField ISBNField;
JTextField quantityField;
JTextField inventoryCostField;
JTextField sellingPriceField;
/**
Constructor: creates frame with all required labels/textboxes/comboboxes.
*/
public AddBookRecordListener()
{
super("Add Book Record");
setSize(400, 300);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLayout(new BorderLayout());
setResizable(false);
// create all required components
JLabel titleLabel = new JLabel("Title(text):");
titleField = new JTextField(NUMBER_OF_CHARS);
JLabel categoryLabel = new JLabel("Category(choose):");
String[] categoryChoices =
{"Novel", "Children", "Hobby", "Computing",
"Accounting", "Other"};
categoryBox = new JComboBox(categoryChoices);
JLabel authorLabel = new JLabel("Author(s)(text):");
authorField = new JTextField(NUMBER_OF_CHARS);
JLabel publisherLabel = new JLabel("Publisher(text):");
publisherField = new JTextField(NUMBER_OF_CHARS);
JLabel yearOfPublicationLabel =
new JLabel("Year of Publication(1000-2100):");
yearOfPublicationField = new JTextField(NUMBER_OF_CHARS);
JLabel ISBNLabel = new JLabel("Enter ISBN Number(integer):");
ISBNField = new JTextField(NUMBER_OF_CHARS);
JLabel quantityLabel = new JLabel("Enter quantity(integer):");
quantityField = new JTextField(NUMBER_OF_CHARS);
JLabel inventoryCostLabel = new JLabel("Inventory Cost(decimal):");
inventoryCostField = new JTextField(NUMBER_OF_CHARS);
JLabel sellingPriceLabel = new JLabel("Selling Price(decimal):");
sellingPriceField = new JTextField(NUMBER_OF_CHARS);
JButton OKButton = new JButton("OK");
OKButton.addActionListener(this);
// create panels
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(9, 2));
JPanel southPanel = new JPanel();
// add all required components
centerPanel.add(titleLabel);
centerPanel.add(titleField);
centerPanel.add(categoryLabel);
centerPanel.add(categoryBox);
centerPanel.add(authorLabel);
centerPanel.add(authorField);
centerPanel.add(publisherLabel);
centerPanel.add(publisherField);
centerPanel.add(yearOfPublicationLabel);
centerPanel.add(yearOfPublicationField);
centerPanel.add(ISBNLabel);
centerPanel.add(ISBNField); // set using constructor only
centerPanel.add(quantityLabel);
centerPanel.add(quantityField);
centerPanel.add(inventoryCostLabel);
centerPanel.add(inventoryCostField);
centerPanel.add(sellingPriceLabel);
centerPanel.add(sellingPriceField);
southPanel.add(OKButton);
add(centerPanel, BorderLayout.CENTER);
add(southPanel, BorderLayout.SOUTH);
}
/**
Precondition: all values must be valid as specified by labels,
and ISBN must be a new value that no other BookRecord object has.
Postcondition: creates a new BookRecord object with the specified
values and adds it to the BookRecordKeeper object.
@param evt the event being fired
*/
public void actionPerformed(ActionEvent evt)
{
setVisible(true);
if(evt.getActionCommand().equals("OK")) // makes frame reusable
{
try
{
BookRecord tempRecord =
new BookRecord(ISBNField.getText());
// if ISBN already exists
if(recordListObject.getIndexOfISBN(tempRecord.getISBN()) != -1)
{
throw new ISBNException();
}
// set each instance variable in the record
// using the input in the fields and combo box
tempRecord.setTitle(titleField.getText());
tempRecord.setCategory((String)categoryBox.getSelectedItem());
tempRecord.setAuthor(authorField.getText());
tempRecord.setPublisher(publisherField.getText());
tempRecord.setYearOfPublication(
Integer.parseInt(yearOfPublicationField.getText()));
tempRecord.setQuantity(
Integer.parseInt(quantityField.getText()));
tempRecord.setInventoryCost(
Double.parseDouble(inventoryCostField.getText()));
tempRecord.setSellingPrice(
Double.parseDouble(sellingPriceField.getText()));
// print the new record and dispose frame
recordListObject.add(tempRecord);
printer.setText(tempRecord.toString());
printer.append("\n\t\tNew record added.");
dispose();
}
catch(ISBNException e)
{
JFrame exceptionFrame = new JFrame("Error adding Record");
exceptionFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
exceptionFrame.setSize(300, 200);
JLabel exceptionLabel =
new JLabel("ISBN already exists. Try again.");
exceptionFrame.add(exceptionLabel);
exceptionFrame.setVisible(true);
}
catch(Exception e)
{
JFrame exceptionFrame = new JFrame("Error adding Record");
exceptionFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
exceptionFrame.setSize(300, 200);
JLabel exceptionLabel =
new JLabel("Please read labels carefully. " +
"No negative values.");
exceptionFrame.add(exceptionLabel);
exceptionFrame.setVisible(true);
}
finally
{
clearFields();
}
}
}
/**
Postcondition: clears all textFields in Add Book Record frame.
*/
private void clearFields()
{
titleField.setText("");
authorField.setText("");
publisherField.setText("");
yearOfPublicationField.setText("");
ISBNField.setText("");
quantityField.setText("");
inventoryCostField.setText("");
sellingPriceField.setText("");
}
}
/**
Inner class for Remove Book Record button.
*/
private class RemoveBookRecordListener extends JFrame implements ActionListener
{
private TextField ISBNField;
/**
Constructor: creates frame with 2 labels, 2 textfields and button.
*/
public RemoveBookRecordListener()
{
super("Remove Book Record");
setSize(300, 90);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLayout(new GridLayout(2, 1));
setResizable(false);
JLabel ISBNLabel = new JLabel("Enter ISBN:(integer)");
ISBNField = new TextField(NUMBER_OF_CHARS);
JButton OKButton = new JButton("OK");
OKButton.addActionListener(this);
JPanel top = new JPanel();
top.setLayout(new GridLayout(1, 2));
JPanel bottom = new JPanel();
top.add(ISBNLabel);
top.add(ISBNField);
bottom.add(OKButton);
add(top);
add(bottom);
}
/**
Precondition: ISBN and quantity field must be given valid integers,
and ISBN must be found in ISBN instance variable of a BookRecord object.
Postcondition: removes specified object from the BookRecordKeeper's
ArrayList.
@param evt the event being fired
*/
public void actionPerformed(ActionEvent evt)
{
setVisible(true);
if(evt.getActionCommand().equals("OK")) // makes frame reusable
{
try
{ // assign values to local variables
String ISBN = ISBNField.getText();
int indexOfISBN =
recordListObject.getIndexOfISBN(ISBN);
// print results and dispose frame
recordListObject.remove(indexOfISBN);
printer.setText("\tISBN #" + ISBN +
" removed from records.");
dispose();
}
catch(IndexOutOfBoundsException e)
{
JFrame noChangeFrame = new JFrame("ISBN not found.");
noChangeFrame.setSize(200, 100);
JLabel noChangeLabel =
new JLabel("ISBN number not found.");
noChangeFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
noChangeFrame.add(noChangeLabel);
noChangeFrame.setVisible(true);
}
catch(Exception e)
{
JFrame noChangeFrame = new JFrame("Error removing book record.");
noChangeFrame.setSize(200, 100);
JLabel noChangeLabel =
new JLabel("Positive integer only please.");
noChangeFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
noChangeFrame.add(noChangeLabel);
noChangeFrame.setVisible(true);
}
finally
{
ISBNField.setText("");
}
}
}
}
/**
Inner class for saving to text file.
*/
private class TextIOListener implements ActionListener
{
/**
Constructor: no values must be initialized. Only written here for
clarity.
*/
public TextIOListener()
{
}
/**
Postcondition: determines user's selection and calls corresponding method
accordingly.
@param evt the event being fired
*/
public void actionPerformed(ActionEvent evt)
{
if(evt.getActionCommand().equals("Save to Text File"))
{
saveRecordListToText();
}
else if(evt.getActionCommand().equals("Open from Text File"))
{
openRecordListFromText();
}
}
}
}
BookRecord.java
/**
Assignment 4
@author MasudKhan
This class stores information about a book in a
bookstore.
*/
import java.io.Serializable;
/**
class for storing a BookRecord.
*/
public class BookRecord implements Serializable
{
private String title;
private String category;
private String author;
private String publisher;
private int yearOfPublication;
private String ISBN; // should only be initialized and then never changed
private int quantity;
private int quantitySold;
private double inventoryCost;
private double sellingPrice;
/**
Constructor: initializes object to default values.
*/
public BookRecord()
{
title = "no title";
category = "no category";
author = "no author";
publisher = "no publisher";
yearOfPublication = 1000;
ISBN = "no ISBN";
quantity = 0;
quantitySold = 0;
inventoryCost = 0.0;
sellingPrice = 0.0;
}
/**
Precondition: argument must be an integer value > 0.
Constructor: initializes ISBN using the argument,
because it is the only instance variable with no mutator.
@param theISBN the new BookRecord's ISBN
*/
public BookRecord(String theISBN)
{
ISBN = theISBN;
}
/**
Postcondition: returns the title instance variable of the object.
@return title the title instance variable
*/
public String getTitle()
{
return title;
}
/**
Postcondition: sets title instance variable to parameter value.
@param newTitle the new value for title.
*/
public void setTitle(String newTitle)
{
title = newTitle;
}
/**
Postcondition: returns the value of category instance variable.
@return returns category instance variable
*/
public String getCategory()
{
return category;
}
/**
Postcondition: sets category instance variable to parameter value.
@param newCategory new value for category instance variable.
*/
public void setCategory(String newCategory)
{
category = newCategory;
}
/**
Postcondition: returns value of author instance variable.
@return returns author instance variable
*/
public String getAuthor()
{
return author;
}
/**
Postcondition: sets author instance variable to parameter value.
@param newAuthor new value for author
*/
public void setAuthor(String newAuthor)
{
author = newAuthor;
}
/**
Postcondition: returns publisher instance variable.
@return returns publisher instance variable
*/
public String getPublisher()
{
return publisher;
}
/**
Postcondition: sets publisher to parameter value.
@param newPublisher new value for publisher.
*/
public void setPublisher(String newPublisher)
{
publisher = newPublisher;
}
/**
Postcondition: returns yearOfPublication instance variable.
@return returns yearOfPublication instance variable
*/
public int getYearOfPublication()
{
return yearOfPublication;
}
/**
Precondition: parameter value must be 1000 - 2100.
Postcondition: sets yearOfPublication instance variable to
parameter value.
@param newYearOfPublication new value for yearOfPublication
@throws Exception
*/
public void setYearOfPublication(int newYearOfPublication)
throws Exception
{
if((newYearOfPublication < 1000) ||
(newYearOfPublication > 2100))
{
throw new Exception();
}
yearOfPublication = newYearOfPublication;
}
/**
Postcondition: returns ISBN instance variable.
@return returns ISBN instance variable
*/
public String getISBN()
{
return ISBN;
}
/**
Postconditon: sets ISBN to parameter value.
@param newISBN the new ISBN
*/
public void setISBN(String newISBN)
{
ISBN = newISBN;
}
/**
Postcondition: returns quantity instance variable.
@return returns quantity instance variable
*/
public int getQuantity()
{
return quantity;
}
/**
Precondition: parameter value must be >= 0.
Postcondition: sets quantity instance variable to
parameter value.
@param newQuantity new value for quantity
@throws Exception
*/
public void setQuantity(int newQuantity)
throws Exception
{
if(newQuantity < 0)
{
throw new Exception();
}
quantity = newQuantity;
}
/**
Postcondition: returns quantitySold instance variable.
@return returns quantitySold instance variable
*/
public int getQuantitySold()
{
return quantitySold;
}
/**
Precondition: parameter value must be >= 0.
Postcondition: sets quantitySold instance variable to parameter value.
@param newQuantitySold the new value for quantitySold instance variable
@throws Exception
*/
public void setQuantitySold(int newQuantitySold)
throws Exception
{
if(newQuantitySold < 0)
{
throw new Exception();
}
quantitySold = newQuantitySold;
}
/**
Postcondition: returns inventoryCost instance variable.
@return returns inventoryCost instance variable
*/
public double getInventoryCost()
{
return inventoryCost;
}
/**
Precondition: parameter value must be >= 0.0.
Postcondition: sets inventoryCost to parameter value.
@param newInventoryCost new value for inventoryCost
@throws Exception
*/
public void setInventoryCost(double newInventoryCost)
throws Exception
{
if(newInventoryCost < 0.0)
{
throw new Exception();
}
inventoryCost = newInventoryCost;
}
/**
Postcondition: returns selling Price instance variable.
@return returns sellingPrice instance variable
*/
public double getSellingPrice()
{
return sellingPrice;
}
/**
Precondition: parameter value must be >= 0.0.
Postcondition: sets sellingPrice instance variable to
parameter value.
@param newSellingPrice new value for sellingPrice.
@throws Exception
*/
public void setSellingPrice(double newSellingPrice)
throws Exception
{
if(newSellingPrice < 0.0)
{
throw new Exception();
}
sellingPrice = newSellingPrice;
}
/**
Postcondition: returns string of all object information.
@return returns string containing Record Info
*/
public String toString()
{
return ("Title: " + title +
"\nCategory: " + category +
"\nAuthor: " + author +
"\nPublisher: " + publisher +
"\nYear Of Publication: " + yearOfPublication +
"\nISBN: " + ISBN +
"\nQuantity: " + quantity +
"\nQuantity Sold: " + quantitySold +
"\nInventory Cost: $" + inventoryCost +
"\nSelling Price: $" + sellingPrice +
"\nPotential Profit: $" + getPotentialProfit() +
"\n");
}
/**
Postcondition: returns total potential profit, which is calculated
by subtracting total cost of all copies from total sales of all copies.
@return returns the calculated potential profit
*/
public double getPotentialProfit()
{
return((sellingPrice * quantity) - (inventoryCost * quantity));
}
}
BookRecordKeeper.java
<pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee;font-size: 12px;border: 1px dashed #999999;line-height: 14px;padding: 5px; overflow: auto; width: 100%"><code>/**
Assignment 4
@author MasudKhan
This class stores information about a book in a
bookstore.
*/
import java.io.Serializable;
/**
class for storing a BookRecord.
*/
public class BookRecord implements Serializable
{
private String title;
private String category;
private String author;
private String publisher;
private int yearOfPublication;
private String ISBN; // should only be initialized and then never changed
private int quantity;
private int quantitySold;
private double inventoryCost;
private double sellingPrice;
/**
Constructor: initializes object to default values.
*/
public BookRecord()
{
title = "no title";
category = "no category";
author = "no author";
publisher = "no publisher";
yearOfPublication = 1000;
ISBN = "no ISBN";
quantity = 0;
quantitySold = 0;
inventoryCost = 0.0;
sellingPrice = 0.0;
}
/**
Precondition: argument must be an integer value > 0.
Constructor: initializes ISBN using the argument,
because it is the only instance variable with no mutator.
@param theISBN the new BookRecord's ISBN
*/
public BookRecord(String theISBN)
{
ISBN = theISBN;
}
/**
Postcondition: returns the title instance variable of the object.
@return title the title instance variable
*/
public String getTitle()
{
return title;
}
/**
Postcondition: sets title instance variable to parameter value.
@param newTitle the new value for title.
*/
public void setTitle(String newTitle)
{
title = newTitle;
}
/**
Postcondition: returns the value of category instance variable.
@return returns category instance variable
*/
public String getCategory()
{
return category;
}
/**
Postcondition: sets category instance variable to parameter value.
@param newCategory new value for category instance variable.
*/
public void setCategory(String newCategory)
{
category = newCategory;
}
/**
Postcondition: returns value of author instance variable.
@return returns author instance variable
*/
public String getAuthor()
{
return author;
}
/**
Postcondition: sets author instance variable to parameter value.
@param newAuthor new value for author
*/
public void setAuthor(String newAuthor)
{
author = newAuthor;
}
/**
Postcondition: returns publisher instance variable.
@return returns publisher instance variable
*/
public String getPublisher()
{
return publisher;
}
/**
Postcondition: sets publisher to parameter value.
@param newPublisher new value for publisher.
*/
public void setPublisher(String newPublisher)
{
publisher = newPublisher;
}
/**
Postcondition: returns yearOfPublication instance variable.
@return returns yearOfPublication instance variable
*/
public int getYearOfPublication()
{
return yearOfPublication;
}
/**
Precondition: parameter value must be 1000 - 2100.
Postcondition: sets yearOfPublication instance variable to
parameter value.
@param newYearOfPublication new value for yearOfPublication
@throws Exception
*/
public void setYearOfPublication(int newYearOfPublication)
throws Exception
{
if((newYearOfPublication < 1000) ||
(newYearOfPublication > 2100))
{
throw new Exception();
}
yearOfPublication = newYearOfPublication;
}
/**
Postcondition: returns ISBN instance variable.
@return returns ISBN instance variable
*/
public String getISBN()
{
return ISBN;
}
/**
Postconditon: sets ISBN to parameter value.
@param newISBN the new ISBN
*/
public void setISBN(String newISBN)
{
ISBN = newISBN;
}
/**
Postcondition: returns quantity instance variable.
@return returns quantity instance variable
*/
public int getQuantity()
{
return quantity;
}
/**
Precondition: parameter value must be >= 0.
Postcondition: sets quantity instance variable to
parameter value.
@param newQuantity new value for quantity
@throws Exception
*/
public void setQuantity(int newQuantity)
throws Exception
{
if(newQuantity < 0)
{
throw new Exception();
}
quantity = newQuantity;
}
/**
Postcondition: returns quantitySold instance variable.
@return returns quantitySold instance variable
*/
public int getQuantitySold()
{
return quantitySold;
}
/**
Precondition: parameter value must be >= 0.
Postcondition: sets quantitySold instance variable to parameter value.
@param newQuantitySold the new value for quantitySold instance variable
@throws Exception
*/
public void setQuantitySold(int newQuantitySold)
throws Exception
{
if(newQuantitySold < 0)
{
throw new Exception();
}
quantitySold = newQuantitySold;
}
/**
Postcondition: returns inventoryCost instance variable.
@return returns inventoryCost instance variable
*/
public double getInventoryCost()
{
return inventoryCost;
}
/**
Precondition: parameter value must be >= 0.0.
Postcondition: sets inventoryCost to parameter value.
@param newInventoryCost new value for inventoryCost
@throws Exception
*/
public void setInventoryCost(double newInventoryCost)
throws Exception
{
if(newInventoryCost < 0.0)
{
throw new Exception();
}
inventoryCost = newInventoryCost;
}
/**
Postcondition: returns selling Price instance variable.
@return returns sellingPrice instance variable
*/
public double getSellingPrice()
{
return sellingPrice;
}
/**
Precondition: parameter value must be >= 0.0.
Postcondition: sets sellingPrice instance variable to
parameter value.
@param newSellingPrice new value for sellingPrice.
@throws Exception
*/
public void setSellingPrice(double newSellingPrice)
throws Exception
{
if(newSellingPrice < 0.0)
{
throw new Exception();
}
sellingPrice = newSellingPrice;
}
/**
Postcondition: returns string of all object information.
@return returns string containing Record Info
*/
public String toString()
{
return ("Title: " + title +
"\nCategory: " + category +
"\nAuthor: " + author +
"\nPublisher: " + publisher +
"\nYear Of Publication: " + yearOfPublication +
"\nISBN: " + ISBN +
"\nQuantity: " + quantity +
"\nQuantity Sold: " + quantitySold +
"\nInventory Cost: $" + inventoryCost +
"\nSelling Price: $" + sellingPrice +
"\nPotential Profit: $" + getPotentialProfit() +
"\n");
}
/**
Postcondition: returns total potential profit, which is calculated
by subtracting total cost of all copies from total sales of all copies.
@return returns the calculated potential profit
*/
public double getPotentialProfit()
{
return((sellingPrice * quantity) - (inventoryCost * quantity));
}
}
</code></pre>
ISBNException.java
/**
Assignment 4
@author MasudKhan
This class stores an exception to be thrown
when there is a problem with an ISBN number
in the Bookstore inventory application.
*/
public class ISBNException extends Exception
{
/**
Constructor: creates Exception object with a default message.
*/
public ISBNException()
{
super("Cannot change the value in that way.");
}
/**
Constructor: creates Exception object with given message.
@param message the message to be used to create the object.
*/
public ISBNException(String message)
{
super(message);
}
}
That's all the code....if anyone's still reading :P