Greg Anthony

Greenhorn
+ Follow
since Apr 18, 2004
Merit badge: grant badges
For More
Cows and Likes
Cows
Total received
0
In last 30 days
0
Total given
0
Likes
Total received
0
Received in last 30 days
0
Total given
0
Given in last 30 days
0
Forums and Threads
Scavenger Hunt
expand Ranch Hand Scavenger Hunt
expand Greenhorn Scavenger Hunt

Recent posts by Greg Anthony

I have two classes. Class ItemRecord defines the record in my input file and OrderCalculator4 opens the file and should load some arrays up with the data in the file. But it keeps throwing the first ioexception where i have "Error opening file". I have both classes in the same directory which is why I don't import ItemRecord into OrderCalculator. The code for the two classes is below:
/* This class defines an item record */

import java.io.Serializable;
public class ItemRecord implements Serializable {
private int itemNumb;
private String itemDesc;
private double itemPrice;
// no-argument constructor calls other constructor with default values
public ItemRecord()
{
this( 0, "", 0.0 );
}
// initialize a record
public ItemRecord( int id, String desc, double price )
{
setItemNumb( id );
setItemDesc( desc );
setItemPrice( price );
}
// set item number
public void setItemNumb( int id )
{
itemNumb = id;
}
// get item number
public int getItemNumb()
{
return itemNumb;
}
// set item description
public void setItemDesc( String desc )
{
itemDesc = desc;
}
// get item description
public String getItemDesc()
{
return itemDesc;
}
// set item price
public void setItemPrice( double price )
{
itemPrice = price;
}
// get item price
public double getItemPrice()
{
return itemPrice;
}
}
*******************************
/* This program inputs an item number and quantity from a user
and then calculates and displays a line item total and final total.
Line item totals are also written to an output file. */
// Import Java Packages
import java.text.NumberFormat;
import java.util.Locale;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class OrderCalculator4 extends JFrame implements ActionListener {
private JLabel lineItemLabel;
private JButton addNextButton, summaryButton;
private JTextArea summaryArea;
String output2 = ""; //used for the final total output
double subtotal = 0; //running subtotal
Container container = getContentPane();
ObjectInputStream input;

// create US currency format
NumberFormat moneyFormat = NumberFormat.getCurrencyInstance(Locale.US);
//set up GUI
public OrderCalculator4()
{
container.setLayout(new BorderLayout(70,70));
lineItemLabel= new JLabel();
addNextButton = new JButton("Add Another Item");
summaryButton = new JButton("Compute Order Total");
container.add(lineItemLabel,BorderLayout.NORTH);
container.add(addNextButton,BorderLayout.WEST);
container.add(summaryButton,BorderLayout.EAST);
addNextButton.addActionListener(this);
summaryButton.addActionListener(this);
getInputs();
} // end constructor
//gets item number and quantity and processes line item total
public void getInputs(){

double itemTotal; //line item total for one order
String itemNumb; //item number entered by user
String qty; //quantity entered by user
StringBuffer output = new StringBuffer(); //used to redisplay a new line item order for each iteration

int quantity=0; //quantity used in calculation
int searchKey=-1; // -1 if item not found

int itemNumber[] = new int[5];
String desc[] = new String[5];
double itemPrice[] = new double[5];
loadArrays(itemNumber,desc,itemPrice);

do {
//Get item number from user
itemNumb = JOptionPane.showInputDialog("Enter the 2 digit item number:");
try {
searchKey = linearSearch(itemNumber, Integer.parseInt(itemNumb) );
if (searchKey == -1 ) {
JOptionPane.showMessageDialog(null,"Item Number does not exist",
"Invalid Data",JOptionPane.ERROR_MESSAGE);
itemNumb = JOptionPane.showInputDialog("Enter a valid 2 digit item number:");
searchKey = linearSearch(itemNumber, Integer.parseInt(itemNumb) );
}

//Get Quantity from user
qty = JOptionPane.showInputDialog("Enter quantity to be ordered:");
//Convert to proper type
quantity = Integer.parseInt(qty); } //end try block
catch (NumberFormatException numberFormatException) {
JOptionPane.showMessageDialog (this, "Item Number and Quantity must be inputted as positive integers",
"Invalid Number Format",JOptionPane.ERROR_MESSAGE);
} //end catch
} while (searchKey == -1 || quantity <= 0); //even if alpha entered for numbers,
//searchkey remains at -1 and inputs asked for again
itemTotal = quantity * itemPrice[searchKey];
subtotal += itemTotal;
//append each round of output for label
output.append(itemNumb).append(" ").append(desc[searchKey]).append(rightJustify(Integer.toString(quantity))).append(" at")
.append(rightJustify(moneyFormat.format(itemPrice[searchKey]))).append(" ").append(rightJustify(moneyFormat.format(itemTotal)));
lineItemLabel.setText(output.toString());
output.delete(0, output.length()); //clear stringbuffer to append same string with tab char
output.append(itemNumb).append(" ").append(desc[searchKey]).append("\t").append(rightJustify(Integer.toString(quantity))).append(" at")
.append(rightJustify(moneyFormat.format(itemPrice[searchKey]))).append(" ").append(rightJustify(moneyFormat.format(itemTotal)));
output2 += output.toString() + "\n"; //running string for final summary
output.delete(0, output.length()); //clear for next round of input
} //end method getInputs

public void displaySummary() {
double tax;
double finalTotal;
final double taxRate = 0.08;
tax = taxRate * subtotal;
finalTotal = tax + subtotal;
//final total output
output2 += "\n" + "\t\t" +"Order Subtotal" + rightJustify(moneyFormat.format(subtotal));
output2 += "\n" + "\t\t" + "Tax " + rightJustify(moneyFormat.format(tax));
output2 += "\n" + "\t\t" + "Final Total" + " " + rightJustify(moneyFormat.format(finalTotal));

container.removeAll();
container.repaint();
summaryArea = new JTextArea(output2);
summaryArea.setFont(new Font("Courier New",Font.PLAIN,12));
container.add(summaryArea);
container.add(new JScrollPane(summaryArea));
container.validate();
closeFile();
}
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == addNextButton)
getInputs();
if (event.getSource() == summaryButton)
displaySummary();
}
// finds the index of the item number entered
public int linearSearch( int array[], int item )
throws NumberFormatException
{
for (int counter = 0; counter < array.length; counter++ )
if ( array[ counter ] == item )
return counter;
return -1; //item not found
}
// right justify strings representing amounts in a field of 10 spaces
public String rightJustify(String s1)
{
final int fieldWidth = 10;
int spacesNeeded;
String paddedSpaces = "";
spacesNeeded = fieldWidth - s1.length();
for(int count=0 ; count < spacesNeeded; ++count)
paddedSpaces += " ";
return paddedSpaces + s1;
}
public void loadArrays(int itemNumber2[],String desc2[],double itemPrice2[])
{
File inputFile = new File("C:\\product.txt");
ItemRecord record;
try {
input = new ObjectInputStream( new FileInputStream( inputFile ) );
}
catch (IOException ioException) {
JOptionPane.showMessageDialog(this, "Error Opening File","Error",JOptionPane.ERROR_MESSAGE);
}
try {
for (int counter = 0; counter < itemNumber2.length; counter++)
{
record = ( ItemRecord ) input.readObject();
itemNumber2[counter] = record.getItemNumb();
desc2[counter] = record.getItemDesc();
itemPrice2[counter] = record.getItemPrice();
} // end for
} //end try
catch ( EOFException endOfFileException ) {
JOptionPane.showMessageDialog( this, "No more records in file",
"End of File", JOptionPane.ERROR_MESSAGE );
}
catch ( ClassNotFoundException classNotFoundException ) {
JOptionPane.showMessageDialog( this, "Unable to create object",
"Class Not Found", JOptionPane.ERROR_MESSAGE );
}
catch (IOException ioException) {
JOptionPane.showMessageDialog(this, "Error Opening File","Error",JOptionPane.ERROR_MESSAGE);
}

} // end method loadArrays
private void closeFile()
{
// close file and exit
try {
input.close();
System.exit( 0 );
}
// process exception while closing file
catch ( IOException ioException ) {
JOptionPane.showMessageDialog( this, "Error closing file",
"Error", JOptionPane.ERROR_MESSAGE );
System.exit( 1 );
}
} // end method closeFile
public static void main( String args[] )
{
OrderCalculator4 application = new OrderCalculator4();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
} //end class OrderCalculator4
19 years ago