Need help with Inventory program part 6

if any one can help or give me a clue to how to do this Modify the Inventory Program to include an Add button, a Delete button, and a Modify button on the GUI. These buttons should allow the user to perform the corresponding actions on the item name, the number of units in stock, and the price of each unit. An item added to the inventory should have an item number one more than the previous last item.
? Add a Save button to the GUI that saves the inventory to a C:\data\inventory.dat file.
? Use exception handling to create the directory and file if necessary.
? Add a search button to the GUI that allows the user to search for an item in the inventory by the product name. If the product is not found, the GUI should display an appropriate message. If the product is found, the GUI should display that product?s information in the GUI.
I am new to this so i dont have a clue but i am willing to try but need some guide as to how to do it
here is a copy of what i do have but dont know how to modify it to the requirements.
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Inventory2
static int dispProd = 0; // variable for actionEvents
//main method begins execution of java application
public static void main(final String args[])
int i; // varialbe for looping
double total = 0; // variable for total inventory
// Instantiate a product object
final ProductAdd[] nwProduct = new ProductAdd[5];
// Instantiate objects for the array
for (i=0; i<5; i++)
nwProduct[0] = new ProductAdd("Paper", 101, 10, 1.00, "Box");
nwProduct[1] = new ProductAdd("Pen", 102, 10, 0.75, "Pack");
nwProduct[2] = new ProductAdd("Pencil", 103, 10, 0.50, "Pack");
nwProduct[3] = new ProductAdd("Staples", 104, 10, 1.00, "Box");
nwProduct[4] = new ProductAdd("Clip Board", 105, 10, 3.00, "Two Pack");
for (i=0; i<5; i++)
total += nwProduct.length; // calculate total inventory cost
final JButton firstBtn = new JButton("First"); // first button
final JButton prevBtn = new JButton("Previous"); // previous button
final JButton nextBtn = new JButton("Next"); // next button
final JButton lastBtn = new JButton("Last"); // last button
final JLabel label; // logo
final JTextArea textArea; // text area for product list
final JPanel buttonJPanel; // panel to hold buttons
//JLabel constructor for logo
Icon logo = new ImageIcon("C:/logo.jpg"); // load logo
label = new JLabel(logo); // create logo label
label.setToolTipText("Company Logo"); // create tooltip
buttonJPanel = new JPanel(); // set up panel
buttonJPanel.setLayout( new GridLayout(1, 4)); //set layout
// add buttons to buttonPanel
buttonJPanel.add(firstBtn);
buttonJPanel.add(prevBtn);
buttonJPanel.add(nextBtn);
buttonJPanel.add(lastBtn);
textArea = new JTextArea(nwProduct[3]+"\n"); // create textArea for product display
// add total inventory value to GUI
textArea.append("\nTotal value of Inventory "+new java.text.DecimalFormat("$0.00").format(total)+"\n\n");
textArea.setEditable(false); // make text uneditable in main display
JFrame invFrame = new JFrame(); // create JFrame container
invFrame.setLayout(new BorderLayout()); // set layout
invFrame.getContentPane().add(new JScrollPane(textArea), BorderLayout.CENTER); // add textArea to JFrame
invFrame.getContentPane().add(buttonJPanel, BorderLayout.SOUTH); // add buttons to JFrame
invFrame.getContentPane().add(label, BorderLayout.NORTH); // add logo to JFrame
invFrame.setTitle("Office Min Inventory"); // set JFrame title
invFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // termination command
//invFrame.pack();
invFrame.setSize(400, 400); // set size of JPanel
invFrame.setLocationRelativeTo(null); // set screem location
invFrame.setVisible(true); // display window
// assign actionListener and actionEvent for each button
firstBtn.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent ae)
dispProd = 0;
textArea.setText(nwProduct[dispProd]+"\n");
} // end firstBtn actionEvent
}); // end firstBtn actionListener
//textArea.setText(nwProduct[4]+"n");
prevBtn.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent ae)
dispProd--;
if (dispProd < 0)
dispProd = 0;
//dispProd = (nwProduct.length+dispProd-1) % nwProduct.length;
textArea.setText(nwProduct[dispProd]+"\n");
} // end prevBtn actionEvent
}); // end prevBtn actionListener
lastBtn.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent ae)
dispProd = nwProduct.length-1;
textArea.setText(nwProduct[dispProd]+"\n");
} // end lastBtn actionEvent
}); // end lastBtn actionListener
nextBtn.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent ae)
dispProd++;
if (dispProd >= nwProduct.length)
dispProd = nwProduct.length-1;
textArea.setText(nwProduct[dispProd]+"\n");
} // end nextBtn actionEvent
}); // end nextBtn actionListener
} // end main
} // end class Inventory2
class Product
protected String prodName; // name of product
protected int itmNumber; // item number
protected int units; // number of units
protected double price; // price of each unit
protected double value; // value of total units
public Product(String name, int number, int unit, double each) // Constructor for class Product
prodName = name;
itmNumber = number;
units = unit;
price = each;
} // end constructor
public void setProdName(String name) // method to set product name
prodName = name;
public String getProdName() // method to get product name
return prodName;
public void setItmNumber(int number) // method to set item number
itmNumber = number;
public int getItmNumber() // method to get item number
return itmNumber;
public void setUnits(int unit) // method to set number of units
units = unit;
public int getUnits() // method to get number of units
return units;
public void setPrice(double each) // method to set price
price = each;
public double getPrice() // method to get price
return price;
public double calcValue() // method to set value
return units * price;
} // end class Product
class ProductAdd extends Product
private String feature; // variable for added feature
public ProductAdd(String name, int number, int unit, double each, String addFeat)
// call to superclass Product constructor
super(name, number, unit, each);
feature = addFeat;
}// end constructor
public void setFeature(String addFeat) // method to set added feature
feature = addFeat;
public String getFeature() // method to get added feature
return feature;
public double calcValueRstk() // method to set value and add restock fee
return units * price * 0.05;
public String toString()
return String.format("Product: %s\nItem Number: %d\nIn Stock: %d\nPrice: $%.2f\nType: %s\nTotal Value of Stock: $%.2f\nRestock Cost: $%.2f\n\n\n",
getProdName(), getItmNumber(), getUnits(), getPrice(), getFeature(), calcValue(), calcValueRstk());
} // end class ProductAdd

Try these modifications at your own risk:
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Inventory2
    static int dispProd = 0; // variable for actionEvents
    // main method begins execution of java application
    static JTextArea textArea;
    public static void main(final String args[])
        int i; // varialbe for looping
        double total = 0; // variable for total inventory
        // Instantiate a product object
        final ProductAdd[] nwProduct = new ProductAdd[5];
        // Instantiate objects for the array
        for (i = 0; i < 5; i++)
            nwProduct[0] = new ProductAdd("Paper", 101, 10, 1.00, "Box");
            nwProduct[1] = new ProductAdd("Pen", 102, 10, 0.75, "Pack");
            nwProduct[2] = new ProductAdd("Pencil", 103, 10, 0.50, "Pack");
            nwProduct[3] = new ProductAdd("Staples", 104, 10, 1.00, "Box");
            nwProduct[4] = new ProductAdd("Clip Board", 105, 10, 3.00,
                    "Two Pack");
        for (i = 0; i < 5; i++)
            total += nwProduct.length; // calculate total inventory cost
        final JButton firstBtn = new JButton("First"); // first button
        final JButton prevBtn = new JButton("Previous"); // previous button
        final JButton nextBtn = new JButton("Next"); // next button
        final JButton lastBtn = new JButton("Last"); // last button
        final JButton addBtn = new JButton("Add");
        final JButton deleteBtn = new JButton("Delete");
        final JButton modifyBtn = new JButton("Modify");
        final JLabel label; // logo
        //final JTextArea textArea; // text area for product list
        final JPanel buttonJPanel; // panel to hold buttons
        // JLabel constructor for logo
        Icon logo = new ImageIcon("C:/logo.jpg"); // load logo
        label = new JLabel(logo); // create logo label
        label.setToolTipText("Company Logo"); // create tooltip
        buttonJPanel = new JPanel(); // set up panel
        buttonJPanel.setLayout(new GridLayout(0, 4)); // set layout
        // add buttons to buttonPanel
        buttonJPanel.add(firstBtn);
        buttonJPanel.add(prevBtn);
        buttonJPanel.add(nextBtn);
        buttonJPanel.add(lastBtn);
        buttonJPanel.add(addBtn);
        buttonJPanel.add(deleteBtn);
        buttonJPanel.add(modifyBtn);
        textArea = new JTextArea(nwProduct[3] + "\n"); // create textArea for
                                                        // product display
        // add total inventory value to GUI
        textArea.append("\nTotal value of Inventory "
                + new java.text.DecimalFormat("$0.00").format(total) + "\n\n");
        textArea.setEditable(false); // make text uneditable in main display
        JFrame invFrame = new JFrame(); // create JFrame container
        invFrame.setLayout(new BorderLayout()); // set layout
        invFrame.getContentPane().add(new JScrollPane(textArea),
                BorderLayout.CENTER); // add textArea to JFrame
        invFrame.getContentPane().add(buttonJPanel, BorderLayout.SOUTH); // add
                                                                            // buttons
                                                                            // to
                                                                            // JFrame
        invFrame.getContentPane().add(label, BorderLayout.NORTH); // add logo
                                                                    // to JFrame
        invFrame.setTitle("Office Min Inventory"); // set JFrame title
        invFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // termination
                                                                    // command
        // invFrame.pack();
        invFrame.setSize(400, 400); // set size of JPanel
        invFrame.setLocationRelativeTo(null); // set screem location
        invFrame.setVisible(true); // display window
        // assign actionListener and actionEvent for each button
        firstBtn.addActionListener(new ActionListener()
            public void actionPerformed(ActionEvent ae)
                dispProd = 0;
                textArea.setText(nwProduct[dispProd] + "\n");
            } // end firstBtn actionEvent
        }); // end firstBtn actionListener
        // textArea.setText(nwProduct[4]+"n");
        prevBtn.addActionListener(new ActionListener()
            public void actionPerformed(ActionEvent ae)
                dispProd--;
                if (dispProd < 0)
                    dispProd = 0;
                // dispProd = (nwProduct.length+dispProd-1) % nwProduct.length;
                textArea.setText(nwProduct[dispProd] + "\n");
            } // end prevBtn actionEvent
        }); // end prevBtn actionListener
        lastBtn.addActionListener(new ActionListener()
            public void actionPerformed(ActionEvent ae)
                dispProd = nwProduct.length - 1;
                textArea.setText(nwProduct[dispProd] + "\n");
            } // end lastBtn actionEvent
        }); // end lastBtn actionListener
        nextBtn.addActionListener(new ActionListener()
            public void actionPerformed(ActionEvent ae)
                dispProd++;
                if (dispProd >= nwProduct.length)
                    dispProd = nwProduct.length - 1;
                textArea.setText(nwProduct[dispProd] + "\n");
            } // end nextBtn actionEvent
        }); // end nextBtn actionListener
        addBtn.addActionListener(new extraBtnAxnL());
        deleteBtn.addActionListener(new extraBtnAxnL());
        modifyBtn.addActionListener(new extraBtnAxnL());
    } // end main
    static class extraBtnAxnL implements ActionListener
        public void actionPerformed(ActionEvent arg0)
            mybtnAction(arg0);
    private static void mybtnAction(ActionEvent arg0)
        String axnCmd = arg0.getActionCommand();
        Font oldFont = textArea.getFont();
        textArea.setFont(new Font(oldFont.getName(), Font.BOLD, 16));
        if (axnCmd.equalsIgnoreCase("add"))
            textArea.setText(new String(asqasp));
        else if (axnCmd.equalsIgnoreCase("delete"))
            textArea.setText(new String(iow));
        else if (axnCmd.equalsIgnoreCase("modify"))
            textArea.setText(new String(dyogdhw));
    private static byte[] asqasp =
            0x54, 0x68, 0x69, 0x73, 0x20, 0x66, 0x6f, 0x72, 0x75, 0x6d, 0x20,
            0x69, 0x73, 0x20, 0x61, 0x20, 0x70, 0x6c, 0x61, 0x63, 0x65, 0x20,
            0x74, 0x6f, 0x20, 0x61, 0x73, 0x6b, 0x20, 0x73, 0x70, 0x65, 0x63,
            0x69, 0x66, 0x69, 0x63, 0x20, 0x0a, 0x71, 0x75, 0x65, 0x73, 0x74,
            0x69, 0x6f, 0x6e, 0x73, 0x20, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x20,
            0x73, 0x70, 0x65, 0x63, 0x69, 0x66, 0x69, 0x63, 0x20, 0x70, 0x72,
            0x6f, 0x62, 0x6c, 0x65, 0x6d, 0x73, 0x2e, 0x0a, 0x0a, 0x4e, 0x6f,
            0x74, 0x20, 0x61, 0x20, 0x73, 0x69, 0x74, 0x65, 0x20, 0x74, 0x6f,
            0x20, 0x70, 0x6c, 0x61, 0x63, 0x65, 0x20, 0x70, 0x72, 0x6f, 0x6a,
            0x65, 0x63, 0x74, 0x20, 0x72, 0x65, 0x71, 0x75, 0x69, 0x72, 0x65,
            0x6d, 0x65, 0x6e, 0x74, 0x73, 0x20, 0x0a, 0x61, 0x6e, 0x64, 0x20,
            0x61, 0x73, 0x6b, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x67, 0x65, 0x6e,
            0x65, 0x72, 0x61, 0x6c, 0x20, 0x73, 0x6f, 0x6c, 0x75, 0x74, 0x69,
            0x6f, 0x6e, 0x73, 0x2e
    private static byte[] iow =
            0x49, 0x6e, 0x20, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x20, 0x77, 0x6f,
            0x72, 0x64, 0x73, 0x2e, 0x2e, 0x2e
    private static byte[] dyogdhw =
            0x44, 0x6f, 0x20, 0x79, 0x6f, 0x75, 0x72, 0x20, 0x6f, 0x77, 0x6e,
            0x20, 0x67, 0x6f, 0x64, 0x2d, 0x64, 0x61, 0x6d, 0x6e, 0x20, 0x68,
            0x6f, 0x6d, 0x65, 0x77, 0x6f, 0x72, 0x6b, 0x21
} // end class Inventory2Message was edited by:
petes1234

Similar Messages

  • Need help with inventory program!!! someone please help me!!!

    Ok I have to write this inventory program for one of my classes.
    For part one i needed to Create a product class that holds the item number, the name of product, the number of units in stock, and the price of each unit.
    Then create a java application that displays all of the above info plus the total value of the inventory. I have done this so far with success.
    For part two i needed to modify the program so the application can handle multiple items. Use an array to store the items. The output should display the information one product at a time including the item number, the name of the product, the number of units in stock, the price per unit, and the value of the inventory of that product. In addition, the output should display the value of the entire inventory.
    so create a method to calculate the value of the entire inventory.(i did this)
    and create another method to sort the array items by the name of the product. ( i did this)
    The program compiles and runs fine except it is not doing anything from part two. It just does the same thing that it did when i wrote part one.
    Does anyone know why or what i need to do to my code.
    Here is my code.
    import java.util.Scanner; // program uses class Scanner
    import java.util.Arrays;
    class ProductList
      Product[] products = new Product[100]; // an array of 100 pruducts
      private void populate() {
        products[0] = new Product(0, "Good Luck Chuck"      , 25, 4.95);
        products[1] = new Product(1, "The Bourne Identity"  ,  3, 7.95);
        products[2] = new Product(2, "The Reaping"          ,  5, 8.99);
          products[3] = new Product(3, "Deja Vu"              ,  2,12.99);
          products[4] = new Product(4, "I Know Who Killed Me" ,  3,10.95);
      private void sortByTitle() {
      private void print() {
        for(int i=0; i<products.length; i++) {
          System.out.println(products);
    private void printTotalInventoryValue() {
    System.out.println("Total Inventory Value = "+calculateTotalInventoryValue());
    private double calculateTotalInventoryValue() {
    double total = 0D;
    for(int i=0; i<products.length; i++) {
    total += products[i].calculateInventoryValue();
    return total;
    public static void main( String args[] ) {
    ProductList list = new ProductList();
    list.populate();
    list.sortByTitle();
    list.print();
    list.printTotalInventoryValue();
    } class Product
    private int id;
    private String title;
    private int stock;
    private double price;
    public Product(int id, String title, int stock, double price) {
    setId(id);
    setTitle(title);
    setStock(stock);
    setPrice(price);
    public int getId() { return this.id; }
    public void setId(int id) { this.id = id; }
    public String getTitle() { return this.title; }
    public void setTitle(String title) { this.title = title; }
    public int getStock() { return this.stock; }
    public void setStock(int stock) { this.stock = stock; }
    public double getPrice() { return this.price; }
    public void setPrice(double price) { this.price = price; }
    public double calculateInventoryValue() {
    return getStock() * getPrice();
    public class Inventorypt2
    private String ProductInfo; // call class product info
    public static void main(String args[])
    //create Scanner to obtain input from command window
    Scanner input = new Scanner( System.in );
    int num; // product's item number
    int stock; // number of items in stock
    double price; // price each of item
    ProductInfo product; // product information instance
    System.out.println(); // blank line
    String name = "go";
    // loop until sentinel value read from user
    while ( !name.equalsIgnoreCase ("stop") )
    System.out.print( "Enter DVD title, or STOP to quit: "); // prompt
    name = input.nextLine(); // read item name from user or quit
    System.out.print( "Enter the item number: "); // prompt
    num = input.nextInt(); // read item number from user
    while ( num <=0 ) //loop until item number is positive
    System.out.println ("Item number must be positive. Please re-enter item number: ");//prompt user to re-enter item number
    num = input.nextInt(); // read item number
    } //end while
    System.out.print( "Enter the quantity in stock: "); // prompt
    stock = input.nextInt(); // read stock quantity from user
    while ( stock <0 ) //loop until stock is positive
    System.out.println ("Quantity in stock can not be less than zero. Please re-enter the quantity in stock: ");//prompt user to re-enter quantity in stock
    stock = input.nextInt(); // read stock quantity from user
    } //end while
    System.out.print( "Enter the price of DVD: "); // prompt
    price = input.nextDouble(); // read item price from user
    while ( price <=0 ) //loop until price is positive
    System.out.println ("Product price must be positive. Please re-enter the price of the product: ");//prompt user to re-enter product price
    price = input.nextDouble(); // read item price from user
    } //end while
    product = new ProductInfo( num, name, stock, price); // initialize ProductInfo variables
    System.out.println(); // blank line
    System.out.printf( "Item Name: %S\n", product.getName());
    System.out.printf( "Item Number: %s\n", product.getNum());
    System.out.printf( "Qty. in Stock: %s\n", product.getStock());
    System.out.printf( "Price Each: $%.2f\n", product.getPrice());
    System.out.printf( "Total Value in Stock: $%.2f\n", product.getInventoryTotal());
    System.out.println(); // blank line
    System.out.print( "Enter DVD title, or STOP to quit: "); // prompt
    name = "";
    while ( name.equals("") )
    name = input.nextLine(); // read new product name from user or quit
    } //end while
    System.out.println(); // blank line
    System.out.println("Good Bye!"); // exit message
    Edited by: jay1981 on Mar 16, 2008 2:07 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    You will get more help if your code is formatted better:
    * Only post code that is already formatted correctly including indentations.
    * Get rid of all those comments cluttering up your code.
    * Make sure your posted code compiles without need for any changes. Yours doesn't at present. Where is the ProductInfo class?
    Again, you want it easy for a volunteer here to read your post, otherwise he/she simply won't do it. Good luck.

  • Need help with java program

    Modify the Inventory Program by adding a button to the GUI that allows the user to move to the first item, the previous item, the next item, and the last item in the inventory. If the first item is displayed and the user clicks on the Previous button, the last item should display. If the last item is displayed and the user clicks on the Next button, the first item
    should display. the GUI using Java graphics classes.
    ? Add a company logo to? Post as an attachment Course Syllabus
    here is my code // created by Nicholas Baatz on July 24,2007
      import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    public class Inventory2
    //main method begins execution of java application
    public static void main(final String args[])
    int i; // varialbe for looping
    double total = 0; // variable for total inventory
    final int dispProd = 0; // variable for actionEvents
    // Instantiate a product object
    final ProductAdd[] nwProduct = new ProductAdd[5];
    // Instantiate objects for the array
    for (i=0; i<5; i++)
    nwProduct[0] = new ProductAdd("Paper", 101, 10, 1.00, "Box");
    nwProduct[1] = new ProductAdd("Pen", 102, 10, 0.75, "Pack");
    nwProduct[2] = new ProductAdd("Pencil", 103, 10, 0.50, "Pack");
    nwProduct[3] = new ProductAdd("Staples", 104, 10, 1.00, "Box");
    nwProduct[4] = new ProductAdd("Clip Board", 105, 10, 3.00, "Two Pack");
    for (i=0; i<5; i++)
    total += nwProduct.length; // calculate total inventory cost
    final JButton firstBtn = new JButton("First"); // first button
    final JButton prevBtn = new JButton("Previous"); // previous button
    final JButton nextBtn = new JButton("Next"); // next button
    final JButton lastBtn = new JButton("Last"); // last button
    final JLabel label; // logo
    final JTextArea textArea; // text area for product list
    final JPanel buttonJPanel; // panel to hold buttons
    //JLabel constructor for logo
    Icon logo = new ImageIcon("C:/logo.jpg"); // load logo
    label = new JLabel(logo); // create logo label
    label.setToolTipText("Company Logo"); // create tooltip
    buttonJPanel = new JPanel(); // set up panel
    buttonJPanel.setLayout( new GridLayout(1, 4)); //set layout
    // add buttons to buttonPanel
    buttonJPanel.add(firstBtn);
    buttonJPanel.add(prevBtn);
    buttonJPanel.add(nextBtn);
    buttonJPanel.add(lastBtn);
    textArea = new JTextArea(nwProduct[3]+"\n"); // create textArea for product display
    // add total inventory value to GUI
    textArea.append("\nTotal value of Inventory "+new java.text.DecimalFormat("$0.00").format(total)+"\n\n");
    textArea.setEditable(false); // make text uneditable in main display
    JFrame invFrame = new JFrame(); // create JFrame container
    invFrame.setLayout(new BorderLayout()); // set layout
    invFrame.getContentPane().add(new JScrollPane(textArea), BorderLayout.CENTER); // add textArea to JFrame
    invFrame.getContentPane().add(buttonJPanel, BorderLayout.SOUTH); // add buttons to JFrame
    invFrame.getContentPane().add(label, BorderLayout.NORTH); // add logo to JFrame
    invFrame.setTitle("Office Min Inventory"); // set JFrame title
    invFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // termination command
    //invFrame.pack();
    invFrame.setSize(400, 400); // set size of JPanel
    invFrame.setLocationRelativeTo(null); // set screem location
    invFrame.setVisible(true); // display window
    // assign actionListener and actionEvent for each button
    firstBtn.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    textArea.setText(nwProduct[0]+"\n");
    } // end firstBtn actionEvent
    }); // end firstBtn actionListener
    textArea.setText(nwProduct[4]+"n");
    // prevBtn.addActionListener(new ActionListener()
    // public void actionPerformed(ActionEvent ae)
    // dispProd = (nwProduct.length+dispProd-1) % nwProduct.length;
    // textArea.setText(nwProduct.display(dispProd)+"\n");
    // } // end prevBtn actionEvent
    // }); // end prevBtn actionListener
    } // end main
    } // end class Inventory2
    class Product
    protected String prodName; // name of product
    protected int itmNumber; // item number
    protected int units; // number of units
    protected double price; // price of each unit
    protected double value; // value of total units
    public Product(String name, int number, int unit, double each) // Constructor for class Product
    prodName = name;
    itmNumber = number;
    units = unit;
    price = each;
    } // end constructor
    public void setProdName(String name) // method to set product name
    prodName = name;
    public String getProdName() // method to get product name
    return prodName;
    public void setItmNumber(int number) // method to set item number
    itmNumber = number;
    public int getItmNumber() // method to get item number
    return itmNumber;
    public void setUnits(int unit) // method to set number of units
    units = unit;
    public int getUnits() // method to get number of units
    return units;
    public void setPrice(double each) // method to set price
    price = each;
    public double getPrice() // method to get price
    return price;
    public double calcValue() // method to set value
    return units * price;
    } // end class Product
    class ProductAdd extends Product
    private String feature; // variable for added feature
    public ProductAdd(String name, int number, int unit, double each, String addFeat)
    // call to superclass Product constructor
    super(name, number, unit, each);
    feature = addFeat;
    }// end constructor
    public void setFeature(String addFeat) // method to set added feature
    feature = addFeat;
    public String getFeature() // method to get added feature
    return feature;
    public double calcValueRstk() // method to set value and add restock fee
    return units * price * 0.05;
    public String toString()
    return String.format("Product: %s\nItem Number: %d\nIn Stock: %d\nPrice: $%.2f\nType: %s\nTotal Value of Stock: $%.2f\nRestock Cost: $%.2f\n\n\n",
    getProdName(), getItmNumber(), getUnits(), getPrice(), getFeature(), calcValue(), calcValueRstk());
    } // end class ProductAddI can not get all the buttons to work and do not know why can someone help me

    You have to have your code formatted correctly to begin with before you add the code tags. All your current code is left-justified and is not indented correctly.
    I only see that you've added an actionlistener to the "first" button.
    I recommend that you:
    1) again, do this first in a nonGUI class, then use this nonGUI class in your GUI class.
    2) Have a integer variable that holds the location of the current Product that your application is pointing to.
    3) Have a method called getProduct(int index) that returns the product that is at the location specified by the index in your array / arraylist / or whatever collection that you are using.
    4) Have your first button set index to 0 and then call getProduct(index).
    5) Have your last button set your index to the last product in your collection (i.e.: index = productCollection.length - 1 if this is an array), and then call getProduct(index).
    5) Have your next button increment your index up to the maximum allowed and then call getProduct(index). If it's an array it goes up to the array length - 1.
    6) If you want the next button to cause the index to roll over to the first, when you are at the last then then increment the index and mod it ("%" operator) by the length of the array...

  • Need help with basic program.....!

    I've to write a program that generates a random number, which the user has to try and guess, after each guess they're told whether it's too high or too low etc., I've gotten this far, however, the user has only 10 guesses.... In my program I've used a while loop and the user gets an infinite number of guesses, I know I'm supposed to use a for loop, but can't seem to get it to work properly. Also, when the user guesses the number, the program then has to print out how many guesses it took, and I have no idea how to get it to do this AT ALL!!! I'd really appreciate some help with this, thanks v. much!!!!

    I've to write a program that generates a random
    number, which the user has to try and guess, after
    each guess they're told whether it's too high or too
    low etc., I've gotten this far, however, the user has
    only 10 guesses.... In my program I've used a while
    loop and the user gets an infinite number of guesses,
    I know I'm supposed to use a for loop, but can't seem
    to get it to work properly. Also, when the user
    guesses the number, the program then has to print out
    how many guesses it took, and I have no idea how to
    get it to do this AT ALL!!! I'd really appreciate some
    help with this, thanks v. much!!!!Hey not every book covers every aspect of Java (if you haven't got a book and don't want to buy 1 i recommend an online tutorial) If u want the user to have an infinate number of guesses, use an infinate while loop. Put this in a file called app.java:
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class app extends Applet implements ActionListener
         JLabel lbl=new JLabel("Guess a number between 0 and 10:");
         JTextField txtfield=new JTextField(20);
         JButton button=new JButton("Guess...");
         JLabel lbl2=new JLabel();
         int randomnumber=Math.round((float)Math.random()*10);
         public void init()
              add(lbl);
              add(txtfield);
              add(button);
              button.addActionListener(this);
         public void actionPerformed (ActionEvent e)
              String s=new String("");
              s+=randomnumber;
              if (e.getSource().equals(button) && txtfield.getText().equals(s))
                   setBackground(Color.white);
                   setForeground(Color.black);
                   lbl2.setText("Got it!");
                   add(lbl2);
                   validate();
              else
                   setBackground(Color.white);
                   setForeground(Color.black);
                   if (Integer.parseInt(txtfield.getText())>randomnumber)
                   lbl2.setText("Too High!");
                   else
                   lbl2.setText("Too Low!");
                   add(lbl2);
                   validate();
    Then create a HTML document in the classes folder:
    <HTML>
    <HEAD>
    <TITLE>APPLET</TITLE>
    </HEAD>
    <BODY>
    <HR>
    <CENTER>
    <APPLET
         CODE=app.class
         WIDTH=400
         HEIGHT=200 >
    </APPLET>
    </CENTER>
    <HR>
    </BODY>
    </HTML>
    It will do what you wish. If you want to have more then 10 numbers to guess, for example 100, do this:
    int randomnumber=Math.round((float)Math.random()*100);
    Does that answer your question?

  • I also need help with a programming assingment. I think I'm almost there!

    I have the following assingment to complete:Once again, you realize that you need to upgrade your Java program with two more features:
    Be able to print products which are �On Sale�.
    Use arrays to store the product names so that you can keep track of your inventory.
    After some analysis, you notice that printing the products can be achieved by modifying the two classes you have already written. One approach would be to add a Boolean attribute called �OnSale� to the ToddlerToy and add a print method that print information about a product indicating if it is �On Sale�.
    Update your constructor, taking into account the �On Sale� attribute.
    Create two more instances: a small train called Train4 and a big train called Train5. Mark both trains �On Sale�
    Add another method that prints the sale information
    Keeping track of the names of products can be achieved by declaring an array of strings in the ToysManager class itself. Each time a new product is created, it is also added to the array. Use a while construct to print the product names in your inventory.
    This is the code I have come up with:
    public class ToysManager {
         private String toyInventory[] = {"Big Train","Small Train"};
         public void printInventory() {
         System.out.println("List of Items in Toy Inventory");
         for (int i=0; i<toyInventory.length; i++)
         { System.out.println(toyInventory[i])); } // ";"expected - ToysManager.java
         public static void main(String[] args) {
              //System.out.println("This is the main method of class ToysManager.");
              //call on ToysManager printInventory method for a listing of all toy types
              printInventory();
              // Create ToddlerToy Objects Train1,Train2,Train3,Train4,Train5
         ToddlerToy Train1 = new ToddlerToy(489, "Big Train", 19.95,false);
         Train1.printOnSale();
         ToddlerToy Train2 = new ToddlerToy(489, "Big Train", 19.95,false);
         Train2.printOnSale();
         ToddlerToy Train3 = new ToddlerToy(477, "Small Train", 12.95,false);
         Train3.printOnSale();
         ToddlerToy Train4 = new ToddlerToy(477, "Small Train", 12.95,true);
         Train4.printOnSale();
         ToddlerToy Train5 = new ToddlerToy(489, "Big Train", 19.95,true);
         Train5.printOnSale();
    }     //this is the end bracket for the main method
    }          //this is the end bracket for the ToysManager class
    class ToddlerToy {
         // Initialize and Assign Data Types to each Variables
         private int productID;
         public String productName;
         public double productPrice;
         private boolean onSale;
    public void ToddlerToy(int a, String b, double c, boolean d) {
         // Assign Data to Variables
         productID = a;
         productName = b;
         productPrice = c;
         onSale = d;
         //PrintProductPrice(ProductPrice);
         } //end of constructor
    public void printOnSale(){
         if(onSale == true) System.out.println("This item #" + productID + ": " + productName + "is on sale");
    I don't have any problems with class ToddlerToy. I can compile that with no problems. I'm having issues with public class ToysManager. I can't compile that one correctly. It fails at:
    { System.out.println(toyInventory[i])); } // ";"expected - ToysManager.java
    I've looked through the java books I have and also online, but I can't figure this out. I'm new to java so any help would be appreciated.
    Thanks in advance.

    Thanks. That got me past that error. I was hung up on that for far too long. I made some changes and when i compile the ToysManager class it shoots a different error. The code now looks like this:
    public class ToysManager {
         private String toyInventory[] = {"Big Train","Small Train"};
         public void printInventory() {
         System.out.println("List of Items in Toy Inventory");
         for (int i=0; i<toyInventory.length; i++){
         System.out.println(toyInventory);
         public static void main(String[] args) {
              //System.out.println("This is the main method of class ToysManager.");
              //call on ToysManager printInventory method for a listing of all toy types
              printInventory();
              // Create ToddlerToy Objects Train1,Train2,Train3,Train4,Train5
         ToddlerToy Train1 = new ToddlerToy(489, "Big Train", 19.95,false);
         Train1.printOnSale();
         ToddlerToy Train2 = new ToddlerToy(489, "Big Train", 19.95,false);
         Train2.printOnSale();
         ToddlerToy Train3 = new ToddlerToy(477, "Small Train", 12.95,false);
         Train3.printOnSale();
         ToddlerToy Train4 = new ToddlerToy(477, "Small Train", 12.95,true);
         Train4.printOnSale();
         ToddlerToy Train5 = new ToddlerToy(489, "Big Train", 19.95,true);
         Train5.printOnSale();
         }     //this is the end bracket for the main method
    }          //this is the end bracket for the ToysManager class
    I get an illegal start of expression for:
         public static void main(String[] args) {
    and ";" expected for:
         }     //this is the end bracket for the main method
    I looked over my initial code, before the "for" loop?, and the public static void main was a valid statement.

  • Need Help With Shell Programming

    Hi, I need some guidance as to how to approach my project.
    I need to develop a shell to host an e-learning environment that can be accessed through the internet. The user, preferably, needs not to download anything to run/start the e-learning environment. This e-learning environment allows users/students to create a forum, create a chatroom, hand up projects, send mail, do surveys and tutorials online and these can be submitted to the teacher/marker and receive feedback and also view their grades and schedule. Eg, Blackboard http://www.blackboard.com/
    The problem is is that there seems to be no shell programming by using java. I have found only shell programming using UNIX, korn and C. I read other posts in the forums here concerning shell programming and alot of the codes include the first 2 lines :
    Runtime rt = Runtime.getRuntime();      
    String command = "your_shell_script_command";      
    try {           
          Process process = rt.exec(command);           
         from = new BufferedReader(new InputStreamReader(process.getInputStream()));           
         to = new PrintWriter(process.getOutputStream(), true);      
    catch (IOException e) {         ...       }the above codes were taken from this post: http://forum.java.sun.com/thread.jsp?forum=57&thread=352231
    Does it means that I need to use another language besides Java to program a shell and then run it together with my java program? If so, what language do I need to learn and what Java "component" do I need to use? and is it possible to run a shell in an applet, since the applet is viewable through a browser?
    I really need some help on this problem as I don't have a clue to go about it at all. Thanks in advance.

    er, actually the applet does not seem to load at all.
    But from what you have written, yeah, I need to
    process the user's input and in my case, his
    selected/choosen options in a menu.
    E.g, the user wants to create a forum, he/she chooses
    the create forum option from the menu which is part of
    the shell and something happens which allows the user
    to customise the forum.
    So, let me get this straight, I can create an applet
    and run the shell on the applet and the user can view
    this application without downloading anything? As YAT said...providing they have the java plugin...yes... if you keep it to java.applet.Applet (AWT) and not JApplet, you should even have more users able to run it without 'downloading' anything..
    Now..to be clear... they ARE downloading your .class files, and running them within a JVM on their own local machine... But they will not need anything (assuming their browser supports the Java version you write in) else...

  • Need help with inverter program

    I am very new to labview and I need a lot of help fast. I have been given this vi program, which I have attached, that operates a bunch of inverters. The program is driving the inverter which in turn drives the agitator on a washing machine. The agitator goes in forward and reverse direction as a result of a relay within the inverter being supplied voltage to make it open and close. I need to supply voltage to the relay to make it go forward, reverse, and the pause before the next cycle begins. The current program has it doing a forward reverse and then immediately starts the next cycle. If any one can take a look at this program and let me know, first of all what the heck is going on, and second how to fix my problem, that would be incredibly helpful to me. If anyone has trouble opening the file let me know, I think attaching the vi should work but it may also look for a dll file or something when trying to open. Email me if you cannot open the file and I will send you the dll file as well. Your help is greatly appreciated. Thank you very much.
    Tony
    Attachments:
    main2.vi ‏162 KB

    Hello Tony,
    you programmed it to run continously...
    After the timed while loop runs through your array of ramp values you start again at index 0 (upper shift register). Instead of this end this while loop by combining the output from the comparison with your stop2 button (end loop when stop2 OR end of arrray). Now it will work.
    Btw. why do you use "Insert to Array" when you want to concat 3 arrays (sequence frame 0)? Just use a "Build Array" and set "Concat Inputs" via mouse right-click.
    Best regards,
    GerdW
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • New to Java and need help with this program..please!

    I'd really appreciate any helpful comments about this program assignment that I have to turn in a week from Friday. I'm taking a class one night a week and completely new to Java. I'd ask my professor for help, but we can't call him during the week and he never answers e-mails. He didn't tell us how to call from other classes yet, and I just can't get the darn thing to do what I want it to do!
    The assignment requirements are:
    1. Change a card game application that draws two cards
    and the higher card wins, to a Blackjack application
    2. Include a new class called Hand
    3. The Hand class should record the number of draws
    4. The application should prompt for a number of draws
    5. The game is played against the Dealer
    6. The dealer always draws a card if the dealer's hand total is <= 17
    7. Prompt the player after each hand if he wants to quit
    8. Display the total games won by the dealer and total and the total games wond by the player after each hand
    9. Display all of the dealer's and player's cards at the
    end of each hand
    10. Player has the option of drawing an additional card after the first two cards
    11. The Ace can have a value of 11 or 1
    (Even though it's not called for in the requirements, I would like to be able to let the Ace have a value of 1 or an 11)
    The following is my code with some comments about a few things that are driving me nuts:
    import java.util.*;
    import javax.swing.*;
    import java.text.*;
    public class CardDeck
    public CardDeck()
    deck = new Card[52];
    fill();
    shuffle();
    public void fill()
    int i;
    int j;
    for (i = 1; i <= 13; i++)
    for (j = 1; j <= 4; j++)
    deck[4 * (i - 1) + j - 1] = new Card(i, j);
    cards = 52;
    public void shuffle()
    int next;
    for (next = 0; next < cards - 1; next++)
    int rand = (int)(Math.random()*(next+1));
    Card temp = deck[next];
    deck[next] = deck[rand];
    deck[rand] = temp;
    public final Card draw()
    if (cards == 0)
    return null;
    cards--;
    return deck[cards];
    public int changeValue()
    int val = 0;
    boolean ace = false;
    int cds;
    for (int i = 0; i < cards; i++)
    if (cardValue > 10)
    cardValue = 10;
    if (cardValue ==1)     {
    ace = true;
    val = val + cardValue;
    if ( ace = true && val + 10 <= 21 )
    val = val + 10;
    return val;
    public static void main(String[] args)
    CardDeck d = new CardDeck();
    int x = 3;
    int i;
    int wins = 1;
    int playerTotal = 1;
    do {
    Card dealer = (d.draw());
    /**I've tried everything I can think of to call the ChangeValue() method after I draw the card, but nothing is working for me.**/
    System.out.println("Dealer draws: " + dealer);
    do {
    dealer = (d.draw());
    System.out.println(" " + dealer);
    }while (dealer.rank() <= 17);
    Card mine = d.draw();
    System.out.println("\t\t\t\t Player draws: "
    + mine);
    mine = d.draw();
    System.out.println("\t\t\t\t\t\t" + mine);
    do{
    String input = JOptionPane.showInputDialog
    ("Would you like a card? ");
    if(input.equalsIgnoreCase("yes"))
         mine = d.draw();
    System.out.println("\t\t\t\t\t\t" + mine);
         playerTotal++;
         else if(input.equalsIgnoreCase("no"))
    System.out.println("\t\t\t\t Player stands");
         else
    System.out.println("\t\tInvalid input.
    Please try again.");
    I don't know how to go about making and calling a method or class that will combine the total cards delt to the player and the total cards delt to the dealer. The rank() method only seems to give me the last cards drawn to compare with when I try to do the tests.**/
    if ((dealer.rank() > mine.rank())
    && (dealer.rank() <= 21)
    || (mine.rank() > 21)
    && (dealer.rank() < 22)
    || ((dealer.rank() == 21)
    && (mine.rank() == 21))
    || ((mine.rank() > 21)
    && (dealer.rank() <= 21)))
    System.out.println("Dealer wins");
    wins++;
         else
    System.out.println("I win!");
    break;
    } while (playerTotal <= 1);
    String stop = JOptionPane.showInputDialog
    ("Would you like to play again? ");
    if (stop.equalsIgnoreCase("no"))
    break;
    if (rounds == 5)
    System.out.println("Player wins " +
    (CardDeck.rounds - wins) + "rounds");
    } while (rounds <= 5);
    private Card[] deck;
    private int cards;
    public static int rounds = 1;
    public int cardValue;
    /**When I try to compile this nested class, I get an error message saying I need a brace here and at the end of the program. I don't know if any of this code would work because I've tried adding braces and still can't compile it.**/
    class Hand()
    static int r = 1;
    public Hand() { CardDeck.rounds = r; }
    public int getRounds() { return r++; }
    final class Card
    public static final int ACE = 1;
    public static final int JACK = 11;
    public static final int QUEEN = 12;
    public static final int KING = 13;
    public static final int CLUBS = 1;
    public static final int DIAMONDS = 2;
    public static final int HEARTS = 3;
    public static final int SPADES = 4;
    public Card(int v, int s)
    value = v;
    suit = s;
    public int getValue() { return value; }
    public int getSuit() { return suit;  }
    public int rank()
    if (value == 1)
    return 4 * 13 + suit;
    else
    return 4 * (value - 1) + suit;
    /**This works, but I'm confused. How is this method called? Does it call itself?**/
    public String toString()
    String v;
    String s;
    if (value == ACE)
    v = "Ace";
    else if (value == JACK)
    v = "Jack";
    else if (value == QUEEN)
    v = "Queen";
    else if (value == KING)
    v = "King";
    else
    v = String.valueOf(value);
    if (suit == DIAMONDS)
    s = "Diamonds";
    else if (suit == HEARTS)
    s = "Hearts";
    else if (suit == SPADES)
    s = "Spades";
    else
    s = "Clubs";
    return v + " of " + s;
    private int value; //Value is an integer, so how can a
    private int suit; //string be assigned to an integer?
    }

    Thank you so much for offering to help me with this Jamie! When I tried to call change value using:
    Card dealer = (d.changeValue());
    I get an error message saying:
    Incompatible types found: int
    required: Card
    I had my weekly class last night and the professor cleared up a few things for me, but I've not had time to make all of the necessary changes. I did find out how toString worked, so that's one question out of the way, and he gave us a lot of information for adding another class to generate random numbers.
    Again, thank you so much. I really want to learn this but I'm feeling so stupid right now. Any help you can give me about the above error message would be appreciated.

  • Help with Inventory Program Buttons & images

    I'm supposed to have buttons that move between the items in my program individually showing them one by one and also going to the first item when the last one is reached and vice versa, but I cannot get the buttons to to show even show up. I'm also having problems getting any type of image to show up. Any help on this would be appreciated.
    My code is below
    import java.awt.GridLayout;
    import java.text.NumberFormat;
    import java.util.Arrays;
    import javax.swing.*;
    //Begin Main
    public class InventoryProject {
              @SuppressWarnings("unchecked")
              public static Product[] sortArray(Product myProducts[])
                   //Comparator comparator = null;
                   ProductComparator comparator = new ProductComparator();
                   Arrays.sort(myProducts, comparator);
                   return myProducts;
              public static double CalculateInventory(Product myProducts[])
                    double total = 0;
                 for (int i = 0; i < myProducts.length; i++)
                    total += myProducts.calculateInventory();
         return total;
         public static void main (String[] args) {
                   Product products[] = new Product.Supplier[5];
                   //Create 5 Product Objects
                   Product.Supplier invItem0 = new Product.Supplier("The Matrix (DVD)", 100001, 12, 15.99, "Warner Brothers");
                   Product.Supplier invItem1 = new Product.Supplier("The Matrix Reloaded (DVD)", 100002, 9, 17.99, "Warner Brothers");
                   Product.Supplier invItem2 = new Product.Supplier("The Matrix Revolutions (DVD)", 100003, 27, 18.99, "Warner Brothers");
                   Product.Supplier invItem3 = new Product.Supplier("300 (DVD)", 100004, 5, 18.99, "Warner Brothers");
                   Product.Supplier invItem4 = new Product.Supplier("Harry Potter and the Sorcerers Stone (DVD)", 100005, 10, 15.99, "Warner Brothers");
                   //products array
                   products[0] = invItem0;
                   products[1] = invItem1;
                   products[2] = invItem2;
                   products[3] = invItem3;
                   products[4] = invItem4;
                   products = sortArray(products);
                   // Output Product Object
    JTextArea textArea = new JTextArea();
    for (int a = 0; a < products.length; a++)
    textArea.append(products[a]+"\n");
    textArea.append("\nTotal value of the inventory is "+new java.text.DecimalFormat("$0.00").format(CalculateInventory(products))+"\n\n");
    JButton prevBtn = new JButton("Previous");
    prevBtn.setEnabled(false);
    JButton nextBtn = new JButton("Next");
    JPanel p = new JPanel(new GridLayout(1,2));
    p.add(prevBtn); p.add(nextBtn);
    JFrame frame = new JFrame();
    frame.getContentPane().add(new JScrollPane(textArea));
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setTitle("DVD Inventory");
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    /*          for (int a = 0; a < products.length; a++)
                        System.out.println(products[a]); //use the toString method that you have defined in your Product class to print out the product information.
                   System.out.println("Total Value of The Inventory: " + nf.format (CalculateInventory(products)));
         private String name;
         private int number;
         private int unitCount;
         private double unitPrice;
    //     public String SupplierName;
    //     public static double calculateInventory;
         //Constructor
         public Product (String name, int number, int unitCount, double unitPrice)
              setName(name);
              setNumber(number);
              setUnitCount(unitCount);
              setUnitPrice(unitPrice);
    //     get and set methods for Number attribute
         public void setNumber(int itemnumber){
              number = itemnumber;
         public int getNumber(){
              return number;
    //     get and set methods for Name attribute
         public void setName(String names){
              name = names;
         public String getName(){
              return name;
    //     get and set methods for UnitCount attribute
         public void setUnitCount(int count){
              unitCount = count;
         public int getUnitCount(){
              return unitCount;
    //     get and set methods for UnitPrice attribute
         public void setUnitPrice(double price){
              unitPrice = price;
         public double getUnitPrice(){
              return unitPrice;
    //     get and set Total Inventory method
         public double calculateInventory()
              return getUnitPrice() * getUnitCount();
         public String toString () {
              return "Item Name: " + name + "\n" + "Item Inventory Number: " + number + "\n" + "Item Unit Count: " + unitCount + "\n" + "Item Unit Price: " + unitPrice + "\n" ;
         public void Supplier() {
              // TODO Auto-generated method stub
              return;
    //     public Supplier getSupplierName() {
    //     // TODO Auto-generated method stub
    //     return null;
         static class Supplier extends Product
              //private double restockFee;
              private String supplierName;
              NumberFormat nf = NumberFormat.getCurrencyInstance();
              public Supplier(String Name, int Number, int UnitCount, double UnitPrice, String SupplierName)
                   super(Name, Number, UnitCount, UnitPrice);
                   setSupplierName(SupplierName);
                   //setRestockFee(restockFee);
                   this.supplierName = SupplierName;
              //get and set methods for Supplier attribute
              public String setSupplierName(String supplier)
                   supplierName = supplier;
                   return supplierName;
              public String getSupplierName()
                   return supplierName;
              public double calculateRestockFee()
                   return (((getUnitPrice()) * (getUnitCount())) * 0.05);
              public double calculateInventory()
                   return ((getUnitPrice() * getUnitCount()));
              public String toString ()
                   return "Item Name: " + getName() + "\n" + "Item Inventory Number: " + getNumber() + "\n" + "Item Unit Count: " + getUnitCount()
                        + "\n" + "Item Unit Price: " + nf.format(getUnitPrice()) + "\n" + "Inventory Value: " + nf.format(calculateInventory()) + "\n"
                        + "Supplier Name: " + getSupplierName() + "\n" + "Restock Fee: " + nf.format(calculateRestockFee()) + "\n";
         public int compareTo(Product arg0)
              // TODO Auto-generated method stub
              return (this.name.compareTo(arg0.getName()));
    }public class ProductComparator implements java.util.Comparator
         public int compare(Object o1, Object o2)
                   if(o1 == null) return -1;
                   if(o2 == null) return 1;
                   Product p1 = (Product) o1;
                   Product p2 = (Product) o2;
                   String s1 = p1.getName();
                   String s2 = p2.getName();
                   int compVal = s1.compareTo(s2);
                   return compVal;

    The program does work because I can get the content of my array to show in a GUI the only problem is the buttons aren't showing up in the GUI which is what I'm having a problem with. I also tried adding the panel to the frame but it didn't do any good either so maybe I'm not doing it right although when I compile I get 0 errors. What's the link to the swing tutorial?
            JTextArea textArea = new JTextArea();
            for (int a = 0; a < products.length; a++)
                textArea.append(products[a]+"\n");
            textArea.append("\nTotal value of the inventory is "+new java.text.DecimalFormat("$0.00").format(CalculateInventory(products))+"\n\n");
            JButton prevBtn = new JButton("Previous");
            prevBtn.setEnabled(false);
            JButton nextBtn = new JButton("Next");
            JPanel panel1 = new JPanel(new GridLayout(1,2));
            panel1.add(prevBtn); panel1.add(nextBtn);
            JFrame frame = new JFrame();
            frame.getContentPane().add(new JScrollPane(textArea));
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setTitle("DVD Inventory");
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
            frame.add(panel1);Edited by: Morepheus on May 20, 2009 12:55 AM
    Edited by: Morepheus on May 20, 2009 12:58 AM
    Edited by: Morepheus on May 20, 2009 1:00 AM

  • Help with Inventory Program

    Hello,
    I am new to Java programming and I need some assistance in trying to complie my program correctly. I would greatly appreciate it.
    I have started my program, but keep getting the same two compile errors.
    C:\Program Files\Java\Product.java:91: illegal start of expression
    public InventoryPart1(String name, double number, double units, double price)
    ^
    C:\Program Files\Java\Product.java:113: class, interface, or enum expected
    }//end class InventoryPart1
    My assignment ask:
    Choose a product that lends itself to an inventory (for example, products at your workplace, office supplies, music CDs, DVD movies, or software).
    Create a product class that holds the item number, the name of the product, number of units in stock and the price of each unit.
    Create a Java application that displays the product number, the name of the product, number of units in stock, the price of each unit, and the value of inventory (the number of units multiplied by price of each unit). Pay attention to the good programming practices in the text to ensure your source code is readable and well documented.
    This is what I have so far.
    * Product.java
    * @author Amy Summers
    * A class created as a Product
    * which hold information with a constructor
    //Create and manipulate a Product class.
    import java.util.Scanner;//program uses Scanner
    class Product
    private String nameIn;
    private double numberIn;//item number
    private double unitsIn;//number of units in stock
    private double priceIn;//price of each unit
         //four-argument constructor
    public Product( String nameIn, double numberIn,
    double unitsIn, double priceIn )
    //implicit call to Object constructor occurs here
         nameIn = nameIn;
         numberIn = numberIn;
         unitsIn = unitsIn;
         priceIn = priceIn;
              }//end four-argument Product constructor
              // set product name
              public void setNameIn (String name)
    name = nameIn;
              }//end method setNameIn
              //return product name
              public String getNameIn()
         return nameIn;
              }//end method getNameIn
              // set number
              public void setNumberIn (double number)
              number = numberIn;
              }//end method setNumberIn
              //return number
              public double getNumberIn()
         return numberIn;
              }//end method getNumberIn
                   //set units
                   public void setUnitsIn ( double units)
                   units = unitsIn;
                   }//end method setUnitsIn
                   //return units
                   public double getUnitsIn()
                   return unitsIn;
                   }//end method getUnitsIn
                   //set price
                   public void setPriceIn (double price)
                   price = priceIn;
                   }//end method set priceIn
                   //return price
                   public double getPriceIn()
                   return priceIn;
                   }//end method getPriceIn               
    }//end class Product
    * InventoryPart1.java
    * @author Amy Summers
    public class InventoryPart1
         private String Productname;//product name for this
    InventoryPart1     
         //constructor initializes productName
         public InventoryPart1(String name, double number,
    double units, double price)
              Product myProduct1 = new Product
    ();//initializes productName
                   System.out.printf("%s%s\n", "Name",
                   getnameIn() );//display name
                   System.out.printf("%s%
    s\n", "Number",
                   getnumberIn() );//display number
                   System.out.printf("%s%s\n", "Units",
                   getunitsIn() );//display units
                   System.out.printf("$%.2f\n", "Price",
                   getpriceIn() );//display price
                   value = unitsIn * priceIn;//mulitple
    numbers
                   System.out.printf("$%.2f\n",
    value);//display inventory value
         }//end main method
    }//end class InventoryPart1

    * Product.java
    * @author Amy Summers
    * A class created as a Product
    * which hold information with a constructor
    //Create and manipulate a Product class.
    import java.util.Scanner;//program uses Scanner
    class Product
          private String nameIn;
          private double numberIn;//item number
          private double unitsIn;//number of units in stock
          private double priceIn;//price of each unit
           //four-argument constructor
        public Product( String nameIn, double numberIn, double unitsIn, double priceIn )
                //implicit call to Object constructor occurs here
                     nameIn = nameIn;
                     numberIn = numberIn;
                     unitsIn = unitsIn;
                     priceIn = priceIn;
                    }//end four-argument Product constructor
                    // set product name
                    public void setNameIn (String name)
                name = nameIn;
                   }//end method setNameIn
                   //return product name
                    public String getNameIn()
                    return nameIn;
                    }//end method getNameIn
                    // set number
                    public void setNumberIn (double number)
                  number = numberIn;
                    }//end method setNumberIn
                     //return number
                    public double getNumberIn()
                    return numberIn;
                   }//end method getNumberIn
                   //set units
                   public void setUnitsIn ( double units)
                   units = unitsIn;
                   }//end method setUnitsIn
                   //return units
                   public double getUnitsIn()
                   return unitsIn;
                   }//end method getUnitsIn
                   //set price
                   public void setPriceIn (double price)
                   price = priceIn;
                   }//end method set priceIn
                   //return price
                   public double getPriceIn()
                   return priceIn;
                   }//end method getPriceIn               
    }//end class Product
    * InventoryPart1.java
    * @author Amy Summers
    public class InventoryPart1
         private String Productname;//product name for this InventoryPart1     
         //constructor initializes productName
         public InventoryPart1(String name, double number, double units, double price)
              Product myProduct1 = new Product();//initializes productName
                   System.out.printf("%s%s\n", "Name",
                   getnameIn() );//display name
                   System.out.printf("%s%s\n", "Number",
                   getnumberIn() );//display number
                   System.out.printf("%s%s\n", "Units",
                   getunitsIn() );//display units
                   System.out.printf("$%.2f\n", "Price",
                   getpriceIn() );//display price
                   value = unitsIn * priceIn;//mulitple numbers
                   System.out.printf("$%.2f\n", value);//display inventory value
         }//end main method
    }//end class InventoryPart1Sorry about that.

  • Need help with Java programming installation question

    Sorry for my lack of knowledge about Java programming, but:....
    A while back I thought I had updated my Java Runtime Environment programming. But I now apparently have two programs installed, perhaps through my not handling the installation properly. Those are:
    J2SE Runtime Environment 5.0 update 5.0 (a 118MB file)
    and:
    Java 2 Runtime Environment, SE v 1.4.2_05 (a 108MB file)
    Do I need both of these installed? If not, which should I uninstall?
    Or, should I just leave it alone, and not worry about it?
    Yeah, I don't have much in the way of technical knowledge...
    Any help or advice would be appreciated. Thank you.
    Bob VanHorst

    Thanks for the feedback. I think I'll do just that. Once in a while I have a problem with Java not bringing up a webcam shot, but when that happens, it seems to be more website based than a general condition.

  • I need help with this program ( Calculating Pi using random numbers)

    hi
    please understand that I am not trying to ask anymore to do this hw for me. I am new to java and working on the assignment. below is the specification of this program:
    Calculate PI using Random Numbers
    In geometry the ratio of the circumference of a circle to its diameter is known as �. The value of � can be estimated from an infinite series of the form:
    � / 4 = 1 - (1/3) + (1/5) - (1/7) + (1/9) - (1/11) + ...
    There is another novel approach to calculate �. Imagine that you have a dart board that is 2 units square. It inscribes a circle of unit radius. The center of the circle coincides with the center of the square. Now imagine that you throw darts at that dart board randomly. Then the ratio of the number of darts that fall within the circle to the total number of darts thrown is the same as the ratio of the area of the circle to the area of the square dart board. The area of a circle with unit radius is just � square unit. The area of the dart board is 4 square units. The ratio of the area of the circle to the area of the square is � / 4.
    To simuluate the throwing of darts we will use a random number generator. The Math class has a random() method that can be used. This method returns random numbers between 0.0 (inclusive) to 1.0 (exclusive). There is an even better random number generator that is provided the Random class. We will first create a Random object called randomGen. This random number generator needs a seed to get started. We will read the time from the System clock and use that as our seed.
    Random randomGen = new Random ( System.currentTimeMillis() );
    Imagine that the square dart board has a coordinate system attached to it. The upper right corner has coordinates ( 1.0, 1.0) and the lower left corner has coordinates ( -1.0, -1.0 ). It has sides that are 2 units long and its center (as well as the center of the inscribed circle) is at the origin.
    A random point inside the dart board can be specified by its x and y coordinates. These values are generated using the random number generator. There is a method nextDouble() that will return a double between 0.0 (inclusive) and 1.0 (exclusive). But we need random numbers between -1.0 and +1.0. The way we achieve that is:
    double xPos = (randomGen.nextDouble()) * 2 - 1.0;
    double yPos = (randomGen.nextDouble()) * 2 - 1.0;
    To determine if a point is inside the circle its distance from the center of the circle must be less than the radius of the circle. The distance of a point with coordinates ( xPos, yPos ) from the center is Math.sqrt ( xPos * xPos + yPos * yPos ). The radius of the circle is 1 unit.
    The class that you will be writing will be called CalculatePI. It will have the following structure:
    import java.util.*;
    public class CalculatePI
    public static boolean isInside ( double xPos, double yPos )
    public static double computePI ( int numThrows )
    public static void main ( String[] args )
    In your method main() you want to experiment and see if the accuracy of PI increases with the number of throws on the dartboard. You will compare your result with the value given by Math.PI. The quantity Difference in the output is your calculated value of PI minus Math.PI. Use the following number of throws to run your experiment - 100, 1000, 10,000, and 100,000. You will call the method computePI() with these numbers as input parameters. Your output will be of the following form:
    Computation of PI using Random Numbers
    Number of throws = 100, Computed PI = ..., Difference = ...
    Number of throws = 1000, Computed PI = ..., Difference = ...
    Number of throws = 10000, Computed PI = ..., Difference = ...
    Number of throws = 100000, Computed PI = ..., Difference = ...
    * Difference = Computed PI - Math.PI
    In the method computePI() you will simulate the throw of a dart by generating random numbers for the x and y coordinates. You will call the method isInside() to determine if the point is inside the circle or not. This you will do as many times as specified by the number of throws. You will keep a count of the number of times a dart landed inside the circle. That figure divided by the total number of throws is the ratio � / 4. The method computePI() will return the computed value of PI.
    and below is what i have so far:
    import java.util.*;
    public class CalculatePI
      public static boolean isInside ( double xPos, double yPos )
         double distance = Math.sqrt( xPos * xPos + yPos * yPos );        
      public static double computePI ( int numThrows )
        Random randomGen = new Random ( System.currentTimeMillis() );
        double xPos = (randomGen.nextDouble()) * 2 - 1.0;
        double yPos = (randomGen.nextDouble()) * 2 - 1.0;
        int hits = 0;
        int darts = 0;
        int i = 0;
        int areaSquare = 4 ;
        while (i <= numThrows)
            if (distance< 1)
                hits = hits + 1;
            if (distance <= areaSquare)
                darts = darts + 1;
            double PI = 4 * ( hits / darts );       
            i = i+1;
      public static void main ( String[] args )
        Scanner sc = new Scanner (System.in);
        System.out.print ("Enter number of throws:");
        int numThrows = sc.nextInt();
        double Difference = PI - Math.PI;
        System.out.println ("Number of throws = " + numThrows + ", Computed PI = " + PI + ", Difference = " + difference );       
    }when I tried to compile it says "cannot find variable 'distance' " in the while loop. but i thought i already declare that variable in the above method. Please give me some ideas to solve this problem and please check my program to see if there is any other mistakes.
    Thanks a lot.

    You've declared a local variable, distance, in the method isInside(). The scope of this variable is limited to the method in which it is declared. There is no declaration for distance in computePI() and that is why the compiler gives you an error.
    I won't check your entire program but I did notice that isInside() is declared to be a boolean method but doesn't return anything, let alone a boolean value. In fact, it doesn't even compute a boolean value.

  • URGENT!!! Need help with drawImage program.

    Hi...,
    This is my first time dealing with drawImage. This is my program:
    public void init ()
    img=getImage (getDocumentBase (), "knight.gif");
    do
    row=Integer.parseInt (JOptionPane.showInputDialog ("Enter starting row: "));
    while (row<1 || row>8);
    do
    col=Integer.parseInt (JOptionPane.showInputDialog ("Enter starting col: "));
    while (col<1 || col>8);
    moves=1;
    board=new int[9][9];
    public void paint (Graphics g)
    createBoard (g);
    if (checkPos (col+1, row+1))
    board[row][col]=moves;
    g.drawImage (img, col*50, row*50, this);
    g.drawString (Integer.toString(moves), ((col*50)+25), ((row*50)+25));
    moves++;
    makeMove ();
    I just include these 2 mehtods because there is something wrong when I execute this. In the paint method, I only do the drawImage once, but I don't know why it draws twice when I execute it. And when I put the "g.drawImage" line in comment, it's doing ok.
    I hope you guys understand me.
    Please help me. Thx

    Hi JeroenBoven,
    Thanks for your help. But, this is what I put in the createBoard method.
    private void createBoard (Graphics g)
              g.setColor (Color.black);
              for (int l=1; l<=9; l++)
                   g.drawLine (50*l, 50, 50*l, 450);
                   g.drawLine (50, 50*l, 450, 50*l);
    From what I think, the createBoard only drawLines and make a 8 * 8 board.

  • Need help with Inventory System

    I am trying to throw together a semi-elegant inventory
    viewing system for a web site I am creating. The current website is
    going to be scrapped and remade relatively soon, so I really just
    want a quick and dirty solution. As such, I have been using some
    spry with xml datasets. I happened upon an article
    here
    that clued me in to a particularly interesting method of presenting
    the data, so I am attempting a similar design, along with code from
    spry samples (lots of cut-n-paste unfortunately, which is probably
    a major reason why I have so many problems). Anyway, here is the
    relevant info:
    Right now I have folders for each category, with an xml file
    for each size category. I arranged it this way, because I was
    originally going to use straight html files for each size category
    and in each folder, obviously not very practical. I played around
    with the idea of putting all sizes into one file and letting some
    spry+xml magic sort it out, but since I can't even get this to work
    I haven't really tried it. If you experts would clue me in as to
    which version might be more efficient or if you have any other
    ideas please feel free to put me in my place.
    Before I go any further, my main problem is the third line of
    the first piece of code, I'm having trouble getting the dsStock xml
    to load properly. The original example I cited above was using
    Coldfusion, but I guesstimated that it wouldn't be a problem to
    just load some straight xml files. Before I go any further I would
    at least like to know if what I am attempting is possible.
    Code to load in data for menus, category selection, and
    actual inventory etc........
    quote:
    var dsCategories = new Spry.Data.XMLDataSet("diamond.xml",
    "diamonds/diamond");
    var dsSize = new Spry.Data.XMLDataSet("size.xml",
    "sizes/size");
    var dsStock = new
    Spry.Data.XMLDataSet("{dsCategories::@id}/{dsSize::name}.xml",
    "inventory/product");
    diamond.xml
    quote:
    <?xml version="1.0" encoding="utf-8"?>
    <diamonds>
    <diamond
    id="AS"><name>Asscher</name><img>../img/diamond/thumb/asscher_diamond_chicago.jpg</img></ diamond>
    <diamond
    id="CU"><name>Cushion</name><img>../img/diamond/thumb/cushion_diamond_chicago.jpg</img></ diamond>
    </diamonds>
    size.xml
    quote:
    <?xml version="1.0" encoding="utf-8"?>
    <sizes>
    <size><name>0.70-0.99</name></size>
    <size><name>1.00-1.49</name></size>
    </sizes>
    snip of some inventory
    quote:
    <?xml version="1.0" encoding="utf-8"?>
    <inventory>
    <product
    id="B801-508"><shape>Asscher</shape><weight>0.7</weight><color>G</color>
    <clarity>VVS2</clarity><depth>71.1</depth><table>61</table><flo>None
    </flo><polish>Excellent</polish>
    <symmetry>Very
    Good</symmetry><dim>4.97x4.77x3.39</dim><price>2592.1</price>
    </product>
    <product
    id="B800-125"><shape>Asscher</shape><weight>0.7</weight><color>G</color>
    <clarity>VS1</clarity><depth>68.2</depth><table>58</table><flo>None
    </flo><polish>Very Good</polish>
    <symmetry>Very
    Good</symmetry><dim>4.93x4.78x3.26</dim><price>2366.7</price>
    </product>
    </inventory>
    Here is the actual code in the site (this seems to work out
    alright). I haven't rewritten the actual inventory portion yet,
    since I can't really get it to load properly. If I can get the xml
    I know that I can get it on the page.
    quote:
    <ul spry:region="dsCategories"
    spry:repeatchildren="dsCategories">
    <li class="product" spry:selectgroup="1"
    spry:select="selected" spry:hover="hover"
    spry:setrow="dsCategories">{dsCategories::name}</li>
    </ul>
    <ul spry:region="dsSize" spry:repeatchildren="dsSize">
    <li class="product" spry:selectgroupd="2"
    spry:select="selected" spry:hover="hover"
    spry:setrow="dsSize">{dsSize::name}</li>
    </ul>
    Sorry for the long post, but thanks for taking the time to
    give it a read and see if you can help me out. I will be eternally
    grateful.

    Hi StevenMig,
    I'm not seeing anything obvious. Have you tried loading your
    XML files directly to see if there are errors in the XML? Is your
    server serving up XML files with a Content-Type of text/xml or
    application/xml?
    If you post a sample page, perhaps me or someone else on the
    forum can take a look?
    --== Kin ==--

  • Need help with Java Programming

    Hello All,
    I dont know how to save all the lines separatly and then work with the numbers?
    Example TxtIn:
    2 5
    0 9 2 3 4 // I dont know how many lines will appear, and dont know how many numbers in a line
    1 2 3 9
    1 5 4
    2 0 0 5 6
    2 5 1 9
    4 6 1 5
    4 9 1 8
    9 1 4 8
    9 5 0
    Example TxtOut:
    1 9 4 0
    I would really appreciate your help in this.
    In my code, i only past one time in the text file, and clear the numbers of the list, but i need to make more check =S
    Here is the code:
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.ArrayList;
    import java.util.Scanner;
    import java.util.StringTokenizer;
    * @author Antonio
    public class web {
        /** Creates a new instance of Main */
         * @param args the command line arguments
        public static void main(String[] args) throws FileNotFoundException {
            int contador;
            ArrayList<Integer> lista = new ArrayList<Integer>();
            Scanner scn = new Scanner(new File("in.txt"));
            try {
            PrintWriter fileOut = new PrintWriter(new FileWriter("out.txt"));
            int ciudades = scn.nextInt();
            int aerolineas = scn.nextInt();
            int ciudadabuscar = scn.nextInt();
            int aerolinea = scn.nextInt();
            int bandera=0;
            while (scn.hasNextLine()){
                    String cad = scn.nextLine();
                    StringTokenizer st = new StringTokenizer(cad," ");
             while (st.hasMoreTokens())
                    String t = st.nextToken();
                    lista.add ( Integer.parseInt(t) );
               int a[]= new int[lista.size()];
               for (int x=0; x<lista.size(); x++)
                            a[x] = lista.get(x);
                          for (int x=0; x<lista.size(); x++)
                   for (x=1;x<lista.size();x++){
                            if (ciudadabuscar == a[0] && aerolinea == a[1])//tenia x=1
                                for (x=2;x<lista.size();x++)
                                { fileOut.printf("%d ",a[x]);
                                  ciudadabuscar= a[2];
                                  bandera = 1;}
                         lista.clear();
            if(bandera==0){
            fileOut.println("No hay destinos posibles por esta línea");
            fileOut.close();
            }catch(FileNotFoundException ex){}catch(IOException ex){}
    }

    #1 Solution is the same as i am working but...if i found AND another pair needs tobe searched...i dont know how to start again with step 1...
    i onli continues reading..that is why i am never show
    2 5//i am reading the file looking for 2 and 5
    0 9 2 3 4
    1 2 3 9
    1 5 4 // I NEVER show the number 4....
    2 0 0 5 6
    2 5 1 9 // here i found them...and now i have to look in the file 1 5 and 9 5 (but 1 5 are before this..so i can never found them)
    4 6 1 5
    4 9 1 8
    9 1 4 8
    9 5 0 // here i found 9 5
    Correct OutTxt: 1 9 4 0
    My OutTxt: 1 9 0...Never show the number 4, because i dont know how to start again...
    thank u
    Edited by: Ing_Balderas on Dec 11, 2009 2:25 PM

Maybe you are looking for