Results 1 to 5 of 5
Thread: Array Munipulation help please
- 07-28-2010, 01:37 AM #1
Member
- Join Date
- Jul 2010
- Posts
- 12
- Rep Power
- 0
Array Munipulation help please
Problem 1
I am trying to display First, Last, Next, Previous. I am not having luck tried it several different ways.
Problem 2
Getting Add, Delete, Modify, and Search to work.
If anyone could help with with Problem one that would be great. Here is my code.
Java Code:package framehelper; /** Program: InventoryProgram * File: FrameHelper.java * Summary: Inherits JFrame class to build a window application that * contains label and text fields. * Author: Shannon Jardine * Date: July 25, 2010 **/ import files.Files; import java.text.NumberFormat; // import Java package used to format currency import manufacture.Manufacture; //Import the Manufacture Class import firstnamecomparator.FirstNameComparator; //Import the FirstNameComparator class import java.awt.GridLayout; // required to create a grid layout import java.awt.BorderLayout; // required to create a border layout import java.awt.event.ActionEvent; // required for click events import java.awt.event.ActionListener; // required for click events import javax.swing.JPanel; // required to create panels import javax.swing.JFrame; // required to use the frame import javax.swing.JButton; // required to create buttons import javax.swing.JLabel; // required to create text fields import javax.swing.JTextField; // required to create text fields import java.util.Arrays; // required to sort array import javax.swing.ImageIcon; // regired to access images import javax.swing.JOptionPane; // required to use message dialog box public class FrameHelper extends JFrame { NumberFormat nf = NumberFormat.getCurrencyInstance(); // used to format currency // Declare Class Variables // Declare two panels. gridPanel is main panel. panel is inserted into // gridPanel. private JPanel gridPanel = new JPanel(); // one panel that contains my gridlayout. private JPanel panel = new JPanel(); // panel used to contain buttons, labels and text fields //NumberFormat nf = NumberFormat.getCurrencyInstance(); // used to format currency // Declare buttons JButton firstButton; // first button JButton nextButton; // next button JButton previousButton; // previous button JButton lastButton; // last button JButton addButton; // add button JButton deleteButton; // delete button JButton modifyButton; // modify button JButton saveButton; // save button JButton searchButton; // search button // Declare Text Fields JTextField nameField; // name field JTextField itemNumberField; // Iem number field JTextField numberOfUnitsInStockField; // Units in Stock field JTextField priceField; // Price of units field JTextField manufactureField; // item manufacture field JTextField totalInventoryField; // sum of the inventory JTextField restockingFeeField; // restock fee field JTextField companyNameField; // company name label // Declare Labels JLabel lblName; // name label JLabel lbItemNumber; // Item label JLabel lblNumberOfUnitsInStock; // Units in Stock label JLabel lblManufacture; // Manufacture label JLabel lblPrice; // Price Label JLabel lblTotalInventory; // total inventory label JLabel lblRestockingFee; // restock fee label JLabel lblLogo; // logo label JLabel lblCompanyName; // company name label // Declare 5 Manufacture objects Manufacture manufacture1; Manufacture manufacture2; Manufacture manufacture3; Manufacture manufacture4; Manufacture manufacture5; public static final int MAX_MANUFACTURES = 5; // set maximum size for Manufacture Array Manufacture[] item = new Manufacture[MAX_MANUFACTURES]; // create Manufacture Array object static int ArrayIndex = 0; // array index public FrameHelper() // constructor { // create and initialize five new Manufacture objects manufacture1 = new Manufacture(); manufacture1.setItemNumber(1); manufacture1.setProductName("Slinks"); manufacture1.setNumberOfUnitsInStock(4); manufacture1.setPriceOfUnit(26.00); manufacture1.setManufacture("PD"); manufacture2 = new Manufacture(); manufacture2.setItemNumber(2); manufacture2.setProductName("Googles"); manufacture2.setNumberOfUnitsInStock(6); manufacture2.setPriceOfUnit(15.00); manufacture2.setManufacture("Flex Vision"); manufacture3 = new Manufacture(); manufacture3.setItemNumber(3); manufacture3.setProductName("LogBook"); manufacture3.setNumberOfUnitsInStock(6); manufacture3.setPriceOfUnit(15.00); manufacture3.setManufacture("Log3"); manufacture4 = new Manufacture(); manufacture4.setItemNumber(4); manufacture4.setProductName("Gloves"); manufacture4.setNumberOfUnitsInStock(4); manufacture4.setPriceOfUnit(12.00); manufacture4.setManufacture("Converse"); manufacture5 = new Manufacture(); manufacture5.setItemNumber(5); manufacture5.setProductName("Closing Loop"); manufacture5.setNumberOfUnitsInStock(18); manufacture5.setPriceOfUnit(2.00); manufacture5.setManufacture("Here Hopin it Opens"); // add Manufacture objects to Array of Manufactures object item[0] = manufacture1; item[1] = manufacture2; item[2] = manufacture3; item[3] = manufacture4; item[4] = manufacture5; gridPanel.setLayout(new BorderLayout()); // create a border layout gridPanel.add(this.createLabelPanel(), BorderLayout.WEST); // add label panel gridPanel.add(this.createTextPanel(), BorderLayout.CENTER); // add field panel gridPanel.add(this.createButtonPanel(), BorderLayout.SOUTH); // add button panel add(gridPanel); } // helper method creates a panel for the button private JPanel createButtonPanel() { ActionListener btnListen = new ButtonListener(); // create listener // create button objects firstButton = new JButton("First"); // create button object firstButton.setActionCommand("First"); // add actionCommand firstButton.addActionListener(btnListen); // add Listener command nextButton = new JButton("Next"); // create button object nextButton.setActionCommand("Next"); // add actionCommand nextButton.addActionListener(btnListen); // add Listener command previousButton = new JButton("Previous"); // create button object previousButton.setActionCommand("Previous"); // add actionCommand previousButton.addActionListener(btnListen); // add Listener command lastButton = new JButton("Last"); // create button object lastButton.setActionCommand("Last"); // add actionCommand lastButton.addActionListener(btnListen); // add Listener command addButton = new JButton("Add"); // create button object addButton.setActionCommand("Add"); // add actionCommand addButton.addActionListener(btnListen); // add Listener command deleteButton = new JButton("Delete"); // create button object deleteButton.setActionCommand("Delete"); // add actionCommand deleteButton.addActionListener(btnListen); // add Listener command modifyButton = new JButton("Modify"); // create button object modifyButton.setActionCommand("Modify"); // add actionCommand modifyButton.addActionListener(btnListen); // add Listener command saveButton = new JButton("Save"); // create button object saveButton.setActionCommand("Save"); // add actionCommand saveButton.addActionListener(btnListen); // add Listener command searchButton = new JButton("Search"); // create button object searchButton.setActionCommand("Search"); // add actionCommand searchButton.addActionListener(btnListen); // add Listener command // create panel object JPanel panels = new JPanel(); panels.add(firstButton); // add first button to panel panels.add(nextButton); // add next button to panel panels.add(previousButton); // add previous button to panel panels.add(lastButton); // add last button to panel panels.add(addButton); // add add button to panel panels.add(deleteButton); // add delete button to panel panels.add(modifyButton); // add modify button to panel panels.add(saveButton); // add save button to panel panels.add(searchButton); // add search button to panel return panels; // return panel } // end createButtonPanel method private JPanel createLabelPanel() { // create instance of label objects ImageIcon icon = new ImageIcon(".\\src\\FarNorthLogo.jpg"); // load the image file lblLogo = new JLabel(icon); // add the image to the label lblName = new JLabel("Name:"); // label for name of item lbItemNumber = new JLabel("Item:"); // label for name of item lblNumberOfUnitsInStock = new JLabel("Units in Stock:"); // label for items in stock lblManufacture = new JLabel("Manufacture:"); // label for manufacture color lblPrice = new JLabel("Price");// Label price lblRestockingFee = new JLabel("Sum of inv:"); lblTotalInventory = new JLabel("Restockin"); // label for restocking fee panel = new JPanel(); panel.setLayout(new GridLayout(8, 2)); // add labels to the panel panel.add(lblLogo); panel.add(lblName); panel.add(lbItemNumber); panel.add(lblNumberOfUnitsInStock); panel.add(lblManufacture); panel.add(lblPrice); panel.add(lblRestockingFee); panel.add(lblTotalInventory); return panel; } // end createLabelPanel method private JPanel createTextPanel() { //create instances of text box objects JLabel lblCompanyName1 = new JLabel(" Far North Skydive Center"); // label for company name nameField = new JTextField(); // name text field nameField.setEditable(false); // set field to not editable to prevent user from changing the data itemNumberField = new JTextField(); // name text field itemNumberField.setEditable(false); // set field to not editable to prevent user from changing the data numberOfUnitsInStockField = new JTextField(); // age text field numberOfUnitsInStockField.setEditable(false); // set field to not editable to prevent user from changing the data manufactureField = new JTextField(); // manufacture text field manufactureField.setEditable(false); // set field to not editable to prevent user from changing the data priceField = new JTextField(); // manufacture text field priceField.setEditable(false); // set field to not editable to prevent user from changing the data restockingFeeField = new JTextField(); // restocking fee field restockingFeeField.setEditable(false); // set field to not editable to prevent user from changing the data totalInventoryField = new JTextField(); // total inventory text field to sum the total of the manufacture's ages. totalInventoryField.setEditable(false); // set field to not editable to prevent user from changing the data panel = new JPanel(); // create panel object panel.setLayout(new GridLayout(9, 2)); // create grid layout for fields. panel.add(lblCompanyName1); // logo field panel.add(nameField); // add the name field to the grid layout panel.add(itemNumberField); // add the name field to the grid layout panel.add(numberOfUnitsInStockField); // add the units in stock field to the grid layout panel.add(manufactureField); // add the manufacture field to the grid layout panel.add(priceField); // add the manufacture field to the grid layout panel.add(restockingFeeField); // add the restock field to the grid layout panel.add(totalInventoryField); // add the total inventory field to the grid layout return panel; // return the panel } // end createTextPanel method private void displayProduct() { //totalInventoryField.setText(nf.format.computeRestockingFee.getValueOfInventory()); if (ArrayIndex == -1) { // no product itemNumberField.setText(null); nameField.setText(null); manufactureField.setText(null); numberOfUnitsInStockField.setText(null); priceField.setText(null); restockingFeeField.setText(null); totalInventoryField.setText(null); } else { // get the product by its index Manufacture manufacture = (Manufacture) item[ArrayIndex]; //item[ArrayIndex]; // update the fields itemNumberField.setText(String.valueOf(manufacture.getItemNumber())); nameField.setText(manufacture.getProductName()); manufactureField.setText(manufacture.getManufacture()); numberOfUnitsInStockField.setText(String.valueOf(manufacture.getNumberOfUnitsInStock())); priceField.setText(String.valueOf(nf.format(manufacture.getPriceOfUnit()))); restockingFeeField.setText(String.valueOf(nf.format(manufacture.getRestockingFee()))); } } // nested ButtonListener class class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { // Parameters for the sort method are the girls array and an instance of my FirstNameComparator class Arrays.sort(item, new FirstNameComparator()); // Sort the girls array totalInventoryField.setText(String.valueOf(item[ArrayIndex].getValueOfInventory())); // display the sum of the girl's age Files file = new Files(); // instantiate th efiles //add button functions if (e.getActionCommand() == null ? "First" == null : e.getActionCommand().equals("First")) // if First button is clicked { try { ArrayIndex = 0; // set the value of the array index displayProduct(); } catch (Exception ex) {//Catch exception if any JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage()); // catch errors that can occur } } if (e.getActionCommand() == null ? "Next" == null : e.getActionCommand().equals("Next")) // if Next button is clicked { try { ArrayIndex = ArrayIndex + 1; displayProduct(); } catch (Exception ex) {//Catch exception if any JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage()); // catch errors that can occur } } if (e.getActionCommand() == null ? "Previous" == null : e.getActionCommand().equals("Previous")) // if Previous button is clicked { try { ArrayIndex = ArrayIndex - 1; displayProduct(); } catch (Exception ex) {//Catch exception if any JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage()); // catch errors that can occur } } if (e.getActionCommand() == null ? "Last" == null : e.getActionCommand().equals("Last")) // if Last button is clicked { try { ArrayIndex = 4; displayProduct(); } catch (Exception ex) {//Catch exception if any JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage()); // catch errors that can occur } } if (e.getActionCommand() == null ? "Add" == null : e.getActionCommand().equals("Add")) // if Add button is clicked { try { // code here } catch (Exception ex) {//Catch exception if any JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage()); // catch errors that can occur } } if (e.getActionCommand() == null ? "Delete" == null : e.getActionCommand().equals("Delete")) // if Delete button is clicked { try { // code here } catch (Exception ex) {//Catch exception if any JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage()); // catch errors that can occur } } if (e.getActionCommand() == null ? "Modify" == null : e.getActionCommand().equals("Modify")) // if Modify button is clicked { try { // code here } catch (Exception ex) {//Catch exception if any JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage()); // catch errors that can occur } } if (e.getActionCommand() == null ? "Search" == null : e.getActionCommand().equals("Search")) // if Search button is clicked { try { // code here } catch (Exception ex) {//Catch exception if any JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage()); // catch errors that can occur } } if (e.getActionCommand() == null ? "Save" == null : e.getActionCommand().equals("Save")) // if Save button is clicked { try { file.appendToFile(item[ArrayIndex].getProductName()); file.appendToFile(", "); file.appendToFile(String.valueOf(item[ArrayIndex].getPriceOfUnit())); file.appendToFile(", "); file.appendToFile(item[ArrayIndex].getManufacture()); file.appendToFile(", "); file.appendToFile(String.valueOf(item[ArrayIndex].getTotalInventory())); file.appendToFile(", "); JOptionPane.showMessageDialog(null, item[ArrayIndex].getProductName() + " has been saved to the file."); // message indicating the file has been saved } catch (Exception ex) {//Catch exception if any JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage()); // catch errors that can occur } } // end if } // end actionPerformed } // end class ButonListerner } // end FrameHelperClass
- 07-28-2010, 01:58 AM #2
I assume there are no errors.I am not having luck
Sounds like you have a logic problem that you need to debug.
Have you tried debugging your code to show execution flow and variables as their values change by adding println() statements to the code?
This is an unusual way to find the object that caused the action event.Java Code:if (e.getActionCommand() == null ? "First" == null : e.getActionCommand().equals("First")) // if First button is clicked
One way is to compare the e.getSource() value with a reference to the object.
With the way you've coded it, there are four places in your code where you have typed in the String "First" and all other Button labels. If you mistype any one of them the code fails. There is no way for the compiler to test if you have misspelled a literal. It would be better to use a final String with the value of "First" and use a reference to it in the four places it needs to be. Then the compiler will catch any misspellings.
You have several private packages so no one can run your code.
- 07-28-2010, 02:17 AM #3
Member
- Join Date
- Jul 2010
- Posts
- 12
- Rep Power
- 0
Here is the rest of the code. This is for a class I am in and I am really new at Java. I am having a hard time with the way the my teacher wants us to put the code together. It doesn't flow with me and others keep asking why I am coding this way. Any help would be great thanks.
Java Code:package frameviewer; /** Program: InventoryProgram * File: FrameViewer.java * Summary: Inherits JFrame class to build a window application that contains labels and text fields. * Author: Shannon Jardine * Date: July 25, 2010 **/ import framehelper.FrameHelper; //Import the frame helper class import javax.swing.JFrame; public class FrameViewer { public static void main(String[] args) { JFrame frame = new FrameHelper(); // creat a frame object frame.setSize(400, 450); // set the size of the window - 400 is width, 200 is height frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // close the application frame.setTitle("My Inventory Application"); // set the title of the window frame.setLocationRelativeTo( null ); // center the form frame.setVisible(true); // display form } // end main } // end classJava Code:package Item; /** Program: InventoryProgram * File: item.java * Summary: Methods for the items reside in this class. * Set and Get Products * Author: Shannon Jardine * Date: July 25, 2010 **/ import java.text.NumberFormat; // import Java package used to format currency public class Item {//Begin Item Class NumberFormat nf = NumberFormat.getCurrencyInstance(); // used to format currency private int itemNumber; // Variable to hold item number private String productName; //Variable to hold product name private int numberOfUnitsInStock; //Variable to holds number of units in stock private double priceOfUnit; //Variable to holds price of units private static double valueOfInventory;//Variable to holds value of inventory per item private static double totalInventory;//Variable to holds inventory value public Item(){} // empty constructor public Item( int itemNumberIn, String productNameIn, int numberOfUnitsInStockIn, double priceOfUnitIn) { this.setItemNumber(itemNumberIn); // call the setItemNumber this.setProductName(productNameIn); // call the setProductName this.setNumberOfUnitsInStock(numberOfUnitsInStockIn); // call the setNumberofUnits this.setPriceOfUnit(priceOfUnitIn); // call the setPriceOfUnit } // end Item Constructor public int getItemNumber( ) { return this.itemNumber; }//end getItemNumber method public void setItemNumber(int itemNumberIn) { itemNumber = itemNumberIn; }//end setItemNumber method public String getProductName( ) { return this.productName; }//end getProductName method public void setProductName(String productNameIn) { productName = productNameIn; }//end setProductName method public int getNumberOfUnitsInStock( ) { return this.numberOfUnitsInStock; }//end getNumberOfUnitsInStock method public void setNumberOfUnitsInStock(int numberOfUnitsInStockIn) { numberOfUnitsInStock = numberOfUnitsInStockIn; }//end setNumberOfUnitsInStock method public double getPriceOfUnit( ) { return this.priceOfUnit; }//end getPriceOfUnit method public void setPriceOfUnit(double priceOfUnitIn) { priceOfUnit = priceOfUnitIn; }//end setPriceOfUnit method public double getValueOfInventory() { return this.priceOfUnit * numberOfUnitsInStock; }//end getValueOfInventory method public double getTotalInventory() { return totalInventory; // get the value of the sum of each Items object's value. } // end getTotalInventory method public void getSumOfInventory(double inValue) {// Sum value o getSumOfInventoryf inventory totalInventory = totalInventory + inValue; }//end getSumOfInventory Method /*@Override public String toString() { String itemStr = String.format("%-2s | ", itemNumber); String titleStr = String.format("%-20s | ", productName); String unitsStr = String.format("%4d | ", numberOfUnitsInStock); String costStr = String.format("$ %6.2f | ", priceOfUnit); String valueStr = String.format("$ %8.2f", getTotalInventory()); return itemStr + titleStr + unitsStr + costStr + valueStr; }*/ }// End of Item ClassJava Code:package files; /** Program: GUI FORM Program * File: Files.java * Summary: This class contains one method that creates a file that does not exist and another method that creates and appends data to a file that does exist. * Both methods use file exception handling to catch errors. * Author: Lisa A. Hebert * Date: December 13, 2009 **/ import java.io.*; // import Java class library required to work with files. import javax.swing.JOptionPane; // import JOptionPane required to use message dialog box. public class Files { // create a file public void createFile()throws IOException { File dataFile; // declare file dataFile = new File("c:\\outputFile.dat"); // create instance of new file if (!dataFile.exists()) { // if file does not exist dataFile.createNewFile(); // create the file JOptionPane.showMessageDialog(null, "New file \"c:\\outputFile.dat\" has been created to the c directory."); } else { JOptionPane.showMessageDialog(null, "The specified file already exists."); } } // end Create File public void appendToFile(String inData) { try { FileWriter fstream = new FileWriter("c:\\outputFile.dat", true); // create file if it does not exist and append data. If the file exists, append data BufferedWriter outputFile = new BufferedWriter(fstream); // declare output file outputFile.write(inData); // append text to output file //Close the output stream outputFile.close(); // close the file } // end try catch (Exception e) {//Catch exception if any JOptionPane.showMessageDialog(null, "Error: " + e.getMessage()); // catch errors that can occur } // end catch } } // end class FilesJava Code:/** Program: InventoryProgram * File: FirstNameComparator.java * Summary: sorts array * Author: Shannon Jardine * Date: July 25, 2010 **/ package firstnamecomparator; import Item.Item; //Import Item class import java.util.Comparator; // you must import the Comparator class. public class FirstNameComparator implements Comparator { public int compare(Object itemOne, Object itemTwo) // createing two Item objects to compare first names. { String firstName1 = ((Item)itemOne).getProductName().toUpperCase(); // getProductName is a method in my Item class. Since the FirstNameComparator class inherits the Item class, it is availabe via the item object. String firstName2 = ((Item)itemTwo).getProductName().toUpperCase(); // compare firstname of my Item object 1 with the first name of Items object 2 if (!(firstName1.equals(firstName2))) return firstName1.compareTo(firstName2); else return firstName2.compareTo(firstName1); } // end compare method } // end FirstNameComparator classJava Code:/** Program: InventoryProgram * File: Manufacture.java * Summary: Sub Class of Item Class. Adds a manufacture and restocking fee * Author: Shannon Jardine * Date: July 25, 2010 **/ package manufacture; import Item.Item; //import InventoryProgram.InventoryProgram; public class Manufacture extends Item {//begin Manufacture class private String manufacture; // Manufacture of product private double restockFee = .05; // public void setManufacture(String manufactureIn) { this.manufacture = manufactureIn; //Set Manufacture } public String getManufacture() { return manufacture; // Get Manufacture } public double getRestockingFee() { return restockFee; } public double computeRestockingFee(double valueOfInventoryIn) { return super.getValueOfInventory() + (getValueOfInventory() * restockFee); } }//End Manufacture Class
- 07-28-2010, 02:25 AM #4
You need to learn how to debug your code and understand how it executes.
Have you tried adding some println() statements to the code to show where the code is executing and what the values of variables are.
Did you read and understand my previous post about your code?
- 07-28-2010, 05:41 AM #5
Member
- Join Date
- Jul 2010
- Posts
- 12
- Rep Power
- 0
Similar Threads
-
convert byte array into char array
By kgkamaraj in forum New To JavaReplies: 4Last Post: 09-13-2011, 11:32 AM -
create a 2d char array from a 1D string array
By jschmall12 in forum New To JavaReplies: 1Last Post: 04-27-2010, 09:01 PM -
Convert Char Array to String Array
By Mayur in forum New To JavaReplies: 8Last Post: 10-12-2009, 11:41 AM -
Array length and printing out uninitialized array.
By nicolek808 in forum New To JavaReplies: 4Last Post: 09-10-2009, 09:12 AM -
How to add an integer to a array element and the store that backinto an array.
By Hannguoi in forum New To JavaReplies: 1Last Post: 03-31-2009, 06:40 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks