|  | |  |
07-08-2009, 01:43 PM
|
#1 (permalink)
| | Recruit
Join Date: Jul 2009
Posts: 6
| Need help with part six of inventory program I am very confused and need help. My assignment for this part is due this Sunday night at midnight. Thank you to anyone who can help me understand where I have gone wrong and where to go from here.
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.
• Add a company logo to the GUI using Java graphics classes.
I am not sure where to go. Below is my code and the response from the instructor when I turned it in last week for part 4.
You program did not compile due to some class definition issues. The first error stems from the fact you are defining multiple classes within the source code and the classes are not being correctly defined/ delimited. The following line:
public static void inventory (String args[])
wraps the entire program and causes it to fail as inventory has to be defined as a class at this point. The lines you mentioned in your post do not show up as errors, but there are some syntax errors such as spaces between assignment operators and your declaration of your import declaratives is not valid, based upon the situation mentioned above. You seem to have a good grasp on the GUI development, but you need to address the overall program construction. Code: package inventory;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
import java.lang.Object;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public static void inventory (String args[]){
class DVD {
private String dvdTitle;
private int stockQuantity;
private double Price;
private double itemNumber;
public DVD()
{
}
public DVD(String title, int stock, double price, double item) {
//call to Object constructor
dvdTitle = title;
stockQuantity = stock;
Price = price;
itemNumber = item;
} //end constructor
//set DVD title
public void setdvdTitle(String title) {
setdvdTitle(title);
} //end method
//return dvd Title
public String getdvdTitle() {
return dvdTitle;
} //end method
//set Dvd quantity
public void stockQuantity(int stock) {
stockQuantity = (stock < 0) ? 0 : stock;
} //end method
//return quantity
public double getstockQuantity() {
return stockQuantity;
} //end method
public void setPrice(double price) {
Price = (price < 0.0) ? 0.0 : price;
} //end method S
//return dvd price
public double getPrice() {
return Price;
} //end method
public void setitemNumber(double item) {
itemNumber = (item < 0.0) ? 0.0 : item;
} //end method
//return itemNumber
public double getitemNumber() {
return itemNumber;
} //end method
// calculate inventory value
public double getValue() {
return getPrice() * stockQuantity;
} //end method
double getInventoryValue() {
throw new UnsupportedOperationException("Not yet implemented");
}
Object[] getitemPrice() {
throw new UnsupportedOperationException("Not yet implemented");
}
Object[] value() {
throw new UnsupportedOperationException("Not yet implemented");
}
// end class Dvd
class dvdExt extends DVD{
private String runningLength;
private String Genre;
double rate = 0.05;
private double restockingfee;
public dvdExt(String title, int stock, double price, double item,String runningLength,String Genre)
{
super(title, stock, price, item);
this.runningLength=runningLength;
this.Genre=Genre;
}
public String getRunningLength() {
return runningLength;
}
public String getGenre() {
return Genre;
}
public void setRunningLength(String runningLength) {
this.runningLength = runningLength;
}
public void setGenre(String Genre) {
this.Genre = Genre;
}
public double getRestockingfee() {
return super.getValue()*rate;
}
}
public class Inventory3 {
private Object[] products;
private int numCDs;
// Dvd = new Dvd ("Rocky", 20, 10.00, 100);
public void main(String args[]) {
int maxItems = 10;
long totalInventoryValue=0,totalRestockingFee=0;
dvdExt dvdcollection[] = new dvdExt[maxItems];
try {
String dvdtitle;
double price;
int stock;
String runLength,Genre;
Scanner scanner = new Scanner(System.in);
for (int k = 0; k < dvdcollection.length; k++) {
System.out.println("Input DVD Title " + String.valueOf(k + 1) +
" of " + String.valueOf(maxItems));
dvdtitle = scanner.nextLine();
System.out.println("Input DVD price " + String.valueOf(k + 1) + " of " +
String.valueOf(maxItems));
price = Double.parseDouble( scanner.nextLine());
System.out.println("Input DVD Quantity " + String.valueOf(k + 1) + " of " +
String.valueOf(maxItems));
stock = Integer.parseInt(scanner.nextLine());
System.out.println("Input DVD Running Time " + String.valueOf(k + 1) + " of " +
String.valueOf(maxItems));
runLength = scanner.nextLine();
System.out.println("Input DVD Genre " + String.valueOf(k + 1) + " of " +
String.valueOf(maxItems));
Genre = scanner.nextLine();
dvdcollection[k] = new dvdExt (dvdtitle, stock, price, k + 1,runLength,Genre);
}
} catch (Exception ec) {
System.out.println(ec.getMessage());
System.exit(-1);
}
for (int k = 0; k < maxItems; k++) {
// calculate the total inventory value
totalInventoryValue + = dvdcollection[k].getValue();
totalRestockingFee + = dvdcollection[k].getRestockingfee();
}
System.out.println("Display Inventory");
System.out.println(" ");
for (int k = 0; k < maxItems; k++) {
System.out.println("DVD Title " + dvdcollection[k].getdvdTitle());
System.out.println("DVD Quantity " + String.valueOf
(dvdcollection[k].getstockQuantity()));
System.out.println("DVD Price " + String.valueOf
(dvdcollection[k].getPrice()));
System.out.println("DVD Item Number " + String.valueOf
(dvdcollection[k].getitemNumber()));
System.out.println("DVD Running Time " + dvdcollection[k].getRunningLength());
System.out.println("DVD Genre " + dvdcollection[k].getGenre());
System.out.println("DVD's Total Value " + String.valueOf
(dvdcollection[k].getValue()));
System.out.println("DVD's Restocking Fee " + String.valueOf
(dvdcollection[k].getRestockingfee()));
System.out.println(" ");
}
System.out.println("Inventory Total Value " +String.valueOf(totalInventoryValue));
System.out.println("Inventory Total Value " +String.valueOf(totalRestockingFee));
}
}
//end main
// sort by name
private void sort(DVD[] products) {
//bubble sort
String n=dvdTitle;
for (int search = 1; search < n; search++) {
for (int i = 0; i < n-search; i++) {
if
(products[i].getdvdTitle().compareToIgnoreCase(products[i+1].getdvdTitle()) > 0)
{// swap
DVD temp = (DVD) products[i];
products[i] = products[i+1];
products[i+1] = temp;
}
}
}
}
public int size (int numCDs) {
return numCDs;
}
}
// end
//inventory GUI part 4
import javax.swing.*;
import java.awt.event.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JLabel;
public void static
class Inventory4 JFrame {
//access to inventory
private Inventory theInventory;
//currently displayed product
//index begins at 0, continues to number of product in inventory -1
private int index = 0;
//GUI to display currently selected product
private final JLabel itemNoLabel = new JLabel
(" Item Number");
private JTextField itemNoText;
private final JLabel dvdTitleLabel = new JLabel
(" DVD Title");
private JTextField dvdTitleText;
private final JLabel itemPriceLabel = new JLabel
(" Item Price");
private JTextField itemPriceText;
private final JLabel noinstockLabel = new JLabel
(" No. In Stock");
private JTextField noinstockText;
private final JLabel valueLabel = new JLabel
(" Product Value");
private JTextField valueText;
private final JLabel restockingFeeLabel = new JLabel
(" Restocking Fee");
private JTextField restockingFeeText;
private final JLabel totalValueLabel = new JLabel
(" totalvalueLabel");
private JTextField totalValueText;
private JPanel centerPanel;
private JPanel buttonPanel;
private Object nextbutton;
private Object itemnoText;
private Object itempriceText;
//GUI constructor that creates all GUI elements
InventoryGUI (Inventory inventory,Inventory theIventory,JButton New) {
super ("MaDonna's Inventory");
final Dimension dim = new Dimension (160, 40);
final FlowLayout flo = new FlowLayout (FlowLayout.LEFT);
JPanel jp;
// create object that will store info
theIventory = inventory;
// create GUI for entering product info and setup panel
centerPanel = new JPanel ();
centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.Y_AXIS));
buttonPanel = new JPanel();
JButton firstButton = new JButton("First");
firstButton.addActionListener(new FirstButtonHandler());
buttonPanel.add(firstButton);
JButton previousButton = new JButton ("Previous");
previousButton.addActionListener(new PreviousButtonHandler());
buttonPanel.add(previousButton);
JButton nextButton = new JButton("Next");
nextbutton.addActionListener(new NextButtonHandler());
buttonPanel.add(nextButton);
JButton lastButton = new JButton("Add");
lastButton.addActionListener(new LastButtonHandler());
buttonPanel.add(lastButton);
JButton addButton = new JButton("Add");
addButton.addActionListener(new AddButtonHandler());
buttonPanel.add(addButton);
JButton deleteButton = new JButton("Delete");
deleteButton.addActionListener(new DeleteButtonHandler());
buttonPanel.add(deleteButton);
JButton modifyButton = new JButton("Modify");
modifyButton.addActionListener(new ModifyButtonHandler());
buttonPanel.add(modifyButton);
JButton saveButton = new JButton("Save");
saveButton.addActionListener(new SaveButtonHandler());
buttonPanel.add(saveButton);
centerPanel.add(buttonPanel);
jp = new JPanel (flo);
itemNoLabel.setPreferredSize(dim);
jp.add(itemNoLabel);
itemNoText = new JTextField(3);
itemNoText.setEditable(false);
jp.add(itemNoText);
centerPanel.add(jp);
jp = new JPanel (flo);
dvdTitleLabel.setPreferredSize(dim);
jp.add(dvdTitleLabel);
dvdTitleLabel = new JTextField(20);
dvdTitleLabel.setEditable(false);
jp.add(dvdTitleText);
centerPanel.add (jp);
jp = new JPanel(flo);
itemPriceLabel.setPreferredSize(dim);
jp.add(itemPriceLabel);
itemPriceText = new JTextField(20);
itemPriceText.setEditable(false);
jp.add(itemPriceText);
centerPanel.add(jp);
jp = new JPanel (flo);
noinstockLabel.setPreferredSize(dim);
jp.add(noinstockLabel);
noinstockText = new JTextField (4);
noinstockText.setEditable(false);
jp.add(noinstockText);
centerPanel.add(jp);
jp = new JPanel (flo);
restockingFeeLabel.setPreferredSize(dim);
jp.add(restockingFeeLabel);
restockingFeeText = new JTextField (20);
restockingFeeText.setEditable(false);
jp.add(restockingFeeText);
centerPanel.add(jp);
jp = new JPanel(flo);
valueLabel.setPreferredSize(dim);
jp.add(valueLabel);
valueText = new JTextField(20);
valueText.setEditable(false);
jp.add(valueText);
centerPanel.add(jp);
//add inventory total
jp = new JPanel (flo);
totalValueLabel.setPreferredSize(dim);
jp.add(totalValueLabel);
totalValueText = new JTextField (20);
totalValueText.setEditable(false);
jp.add(totalValueText);
centerPanel.add(jp);
//add panel to display
setContentPane(centerPanel);
repaintGUI();
setSize(440, 500);
setResizable(false);
setVisible(true);
}
//change display to show current product info
public void repaintGUI() {
DVD temp = (DVD) theInventory.getDVD(index);
if (temp !=null) {
itemnoText.setText("" + temp.getitemNumber());
dvdTitleText.setText(temp.getdvdTitle());
itempriceText.setText(String.format("$%.2f",
temp.getitemPrice()));
restockingFeeText.setText(String.format("$%.2f",
temp.restockingFee()));
noinstockText.setText("" + temp.getnoinstock());
valueText.setText(String.format("$%.2f", temp.value()));
}
totalValueText.setText(String.format("$%.2f",
theInventory.value()));
}
private void setContentPane(JPanel centerPanel) {
setContentPanel();
}
private void setContentPanel() throws UnsupportedOperationException {
throw new UnsupportedOperationException("Not yet implemented");
}
private void setResizable() throws UnsupportedOperationException {
throw new UnsupportedOperationException("Not yet implemented");
}
private void setResizable(boolean b) {
setResizable();
}
private void setSize() throws UnsupportedOperationException {
throw new UnsupportedOperationException("Not yet implemented");
}
private void setSize(int i, int i0) {
throw new UnsupportedOperationException("Not yet implemented");
}
}
private void setSize(int i, int i0) {
setSize();
}
private void setVisible(boolean b) {
throw new UnsupportedOperationException("Not yet implemented");
}
class FirstButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent a){
repaintGUI();
}
private void repaintGUI() {
throw new UnsupportedOperationException("Not yet implemented");
}
}
class PreviousButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent a) {
repaintGUI();
}
private void repaintGUI() {
throw new UnsupportedOperationException("Not yet implemented");
}
}
class NextButtonHandler implements ActionListener {
private Object theInventory;
private int index;
public void actionPerformed(ActionEvent a,int numItems) {
int numitems = theInventory.getnumItems();
index = (++index) % numItems;
repaintGUI();
}
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
private void repaintGUI() {
throw new UnsupportedOperationException("Not yet implemented");
}
}
class LastButtonHandler implements ActionListener {
private Object theInventory;
private int index;
public void actionPerformed(ActionEvent a){
int numItems = theInventory.getNumItems();
index = (numItems -1) % numItems;
repaintGUI();
}
private void repaintGUI() {
throw new UnsupportedOperationException("Not yet implemented");
}
}
class AddButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent a){
repaintGUI();
}
private void repaintGUI() {
throw new UnsupportedOperationException("Not yet implemented");
}
}
class ModifyButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent a) {
repaintGUI();
}
private void repaintGUI() {
throw new UnsupportedOperationException("Not yet implemented");
}
}
class SaveButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent a) {
repaintGUI();
}
private void repaintGUI() {
throw new UnsupportedOperationException("Not yet implemented");
}
}
class DeleteButtonHandler implements ActionListener {
public void actinPerformed(ActionEvent a){
repaintGUI();
}
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
private void repaintGUI() {
throw new UnsupportedOperationException("Not yet implemented");
}
}
}
private void setDefaultCloseOperation(int EXIT_ON_CLOSE) {
throw new UnsupportedOperationException("Not yet implemented");
}
//End Inventory4 class
(THIS IS IN A SEPERATE FILE CALLED INVENTORY)
class Inventory {
int getNumItems() {
int numItems = this.getNumItems();
}
int getnumItems() {
throw new UnsupportedOperationException("Not yet implemented");
}
Object[] value() {
value();
}
private void value() throws UnsupportedOperationException {
throw new UnsupportedOperationException("Not yet implemented");
(THIS IS IN A SEPERATE FILE CALLED - REPAINT)
package inventory;
/**
*
* @author MaDonna
*/
class repaint {
}
Last edited by Belisarius; 07-08-2009 at 02:35 PM.
Reason: Added code tags
|
| |
07-08-2009, 02:39 PM
|
#2 (permalink)
| | Java fanboy
Join Date: Aug 2003
Posts: 1,227
| Your basic problem is what your instructor said - the line Code: public static void inventory (String args[]){ towards the top of your program doesn't make any sense to the compiler. You need to remove that, make sure every "{" has a matching "}" and try to compile the program again.
I need to make a basic syntax tutorial sometime, as that seems to be the biggest hurdle people are having right now. |
| |
07-08-2009, 05:57 PM
|
#3 (permalink)
| | Recruit
Join Date: Jul 2009
Posts: 6
| thank you. I will take that out. If I take this out will I not have to replace it with something else?
Also any suggestions on the part 5 steps?
Thank you so much |
| |
07-08-2009, 07:03 PM
|
#4 (permalink)
| | Java fanboy
Join Date: Aug 2003
Posts: 1,227
| Here is the format of a basic Java class: Code: public <Class Name>{
<variable>
<variable>
<etc>
// This is the "main" method, and there should be only one in your program.
// Don't put this in every class, just one.
static public main(String[] args){
// Code
}
public <return type> <method name>(<method arguments>){
// Code
}
} I would create a new file for each class, but that's just my style. Make sure your program looks something like the above. The compiler will complain if you have the wrong syntax. It's pretty good about giving you useful information - just work one error at a time. One syntax error can cause a cascade of other errors - fixing it will frequently fix a lot of false errors.
I'll take a look at the rest of what you have tomorrow. |
| |
07-09-2009, 06:13 AM
|
#5 (permalink)
| | C++ Beginner
Join Date: Jul 2005 Location: Ottawa
Posts: 87
| To be honest here, I tried spending 10 minutes trying to clean up your code to see what you are doing wrong, and gave up.
You need to go way way way way way back to the basics here, and build something up in units of work that can run. You are not near a stage where you can develop an large application (relative to your experience).
You really need to learn the Java Language Specification The Java Language Specification
and understand the syntax of Java.
What editor are you using? Eclipse or Netbeans? Regardless, get in the habit (and I really suggest you do this now) to split up your classes into separate files. They will be able to see each other and you won't get lost in a chunk of code you just pulled from everywhere into one code block you posted here.
Here's my suggestions to start:
1) Split each class to a seperate file.
2) Indent everything correctly.
3) Get each class to be syntactically correct.
4) Post back here your code in seperate [ code ] [ / code ] tags (one set of tags per file) if you are still having problems.
You have to get on top of this stuff and study the language specification more carefully. It definitely looks like you're behind in your material. |
| |
07-09-2009, 06:19 AM
|
#6 (permalink)
| | C++ Beginner
Join Date: Jul 2005 Location: Ottawa
Posts: 87
| Just to add to this:
1) Follow the naming conventions. Only class definitions begin with capital letters. the rest of the variables are accepted to use camel case.
Here's a sample of what you should do to split your stuff up. I'll be very surprised if you can't figure out what the issues are at this point.
Remember
- everything must be in between a class definition (its opening and closing braces).
- a package declaration, if present, must be the first thing that appears in a java file.
- a java file must be named to match the top level (or first public class) being defined Code: public class DVD {
private ? indentedVariable;
private ? indentedVariableNumberTwo;
...
} Code: /* This is a big hint that dvdExt is not a meaningful name. no one knows what the heck a dvdExt will do or why it extends a DVD with a name like that. */
public class AMeaningfulClassDescription extends DVD {
private ? indentedVariable;
private ? indentedVariableNumberTwo;
public void indentedMethod {
}
} Code: /* Again, think here. what is an Inventory3. why the 3? */
public class Inventory3 {
/* a bunch of indented stuff goes here*/
} Code: /* Again, think here. what is an Inventory4. why the 4? */
public class Inventory4 {
/* a bunch of indented stuff goes here*/
} |
| |
07-09-2009, 04:48 PM
|
#7 (permalink)
| | Recruit
Join Date: Jul 2009
Posts: 6
| Ok. I get that my classe should be in different files. But how do the files talk to each other. I have to make reference in one file to call the other? How do I do that? Yes I am very, very new at this. I am barely getting what I am doing. Using netbbeans I click on the errors and just try to keep eliminating them. |
| |
07-09-2009, 06:26 PM
|
#8 (permalink)
| | Java fanboy
Join Date: Aug 2003
Posts: 1,227
| Java using something called a "CLASSPATH". It's an environmental variable that tells Java "this is where my files are". It will frequently look something like ".;c:/myjavafiles;c:/mylibs". It's a collection of system paths. For the most part, Netbeans will take care of it for you.
Additionally, you use something called "packaging". When you have a statement like Code: import javax.swing.*; you're including all the files in the "javax.swing" package. Java looks through all the files in the CLASSPATH and picks out all the ones that start with Code: package javax.swing; All Java programs start with the "static public void main(String[] args)" method. When you run a Java program, it executes the code in that method. While a Java program can be very large, with many classes and methods, the only one executed when a Java program is run is the "main" method. It's from that method that the rest of the code is called. |
| |
07-10-2009, 07:15 AM
|
#9 (permalink)
| | C++ Beginner
Join Date: Jul 2005 Location: Ottawa
Posts: 87
| To add to what Belisarius said,
you don't worry about instantiation. The fact that all your classes are within a project or project means that they have visibility to each other.
There are a few different types of class visibility, as defined by a few access modifiers that are present in Java.
The access modifiers are as follows: public, private, protected, and on modifier at all (which implies package level visibility).
This is a great read on access to classes: Controlling Access to Members of a Class (The Java™ Tutorials > Learning the Java Language > Classes and Objects)
Split up your files, and the JVM, as one of the services it provides, will be able to take care of your classpath resolution, especially when managed by netbeans which will take care of your compilation and execution.
Don't be afraid to split up your class files. It makes it easier to read and manage for yourself and for other people! |
| |
07-10-2009, 10:09 AM
|
#10 (permalink)
| | Recruit
Join Date: Jul 2009
Posts: 6
| Thank you. this helps. I will continue to work on it this weekend and hopefully come up with something that compiles. I will try to post again tomorrow. I have to work tonight and this weekend.
Thanks! |
| |
07-11-2009, 07:51 AM
|
#11 (permalink)
| | Recruit
Join Date: Jul 2009
Posts: 6
| updated code Code: package Inventory8;
import java.awt.event.*;
import java.awt.Window;
import javax.swing.*;
import javax.swing.JPanel;
//Stores information and retrieves information
public class DVD_Application extends JFrame {
public JTextArea txt;
public Inventory inv;
public int currentDisplay = 0;
public DVD_Application() {
super("DVD Inventory Program");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // quit if the window is closed
init();
}
}
/**
*
* @throws java.lang.UnsupportedOperationException
*/
public void ContentPanel() throws UnsupportedOperationException {
throw new UnsupportedOperationException("Not yet implemented");
}
public void init() {
//create product information
dvdExt p1 = new dvdExt(1, "Some Like It Hot", 10, 8.00, "Classics");
dvdExt p2 = new dvdExt(2, "Liar, Liar", 5, 15.00, "Comedy");
dvdExt p3 = new dvdExt(3, "300", 7, 17.00, "Action");
dvdExt p4 = new dvdExt(4, "Rambo", 5, 10.00, "Action");
}
// create inventory and iput information
inv = new Inventory();
inv.add(p1);
inv.add(p2);
inv.add(p3);
inv.add(p4);
inv.sort();
// output the information
for (int k = 0; k < inv.size(); k++) {
System.out.println("DVD Item number: " + inv.get(k).getItem());
System.out.println("DVD Title: " + inv.get(k).getName());
System.out.println("DVD Quantity in stock: " + inv.get(k).getUnits());
System.out.println("DVD Price: $" + String.format("%.2f",inv.get(k).getPrice()));
System.out.println("DVD Total Inventory Value: $" + String.format("%.2f",inv.get(k).value()));
System.out.println("Restocking Fee: $" + String.format("%.2f",inv.get(k).fee()));
System.out.println();
}
//total val
System.out.println("Total value: $" + String.format("%.2f",inv.value()));
//graphical interface
final JPanel panel = new JPanel();
txt = new JTextArea(25,40); //size of window
txt.setEditable(false);//user unable to edit
panel.add(txt);
final JPanel anotherbuttonpanel = new JPanel();
anotherbuttonpanel.setLayout(new BoxLayout(anotherbuttonpanel,BoxLayout.Y_AXIS));
final JPanel buttonpanel = new JPanel();
buttonpanel.setLayout(new BoxLayout(buttonpanel,BoxLayout.Y_AXIS));
final JButton previous = new JButton("Previous");
previous.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (currentDisplay > 0) currentDisplay--;//method to go to previous
else currentDisplay = inv.size()-1;
displayDVD();
JButton first = new JButton("First");
first.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
currentDisplay = 0;//method to go to beginning
displayDVD(); }
});
buttonpanel.add(previous);
JButton next = new JButton("Next");
next.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (currentDisplay < inv.size()-1) currentDisplay++; //method to go to end
else currentDisplay = 0;
displayDVD();
}
});
buttonpanel.add(next);
JButton last = new JButton("Last");
last.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
currentDisplay = inv.size()-1;//method to go to next item
displayDVD();
}
});
buttonpanel.add(last);
// make the object
dvdExt dvd = new dvdExt(inv.highestNumber()+1, name, units, price, Genre);
// add object to inv
inv.addNewExtendedDVD(dvd);
currentDisplay = inv.size()-1;
displayDVD();
}
});
buttonpanel.add(new Logo());
panel.add(buttonpanel);
panel.add(anotherbuttonpanel);
displayDVD();
}
// display
public void displayDVD() {
txt.setText("DVD Details:\n");
txt.append("DVD Item number: " + inv.get(currentDisplay).getItem() + "\n");
txt.append("DVD Title: " + inv.get(currentDisplay).getName() + "\n");
txt.append("DVD Quantity in Stock: " + inv.get(currentDisplay).getUnits() + "\n");
txt.append("DVD Price: $" + String.format("%.2f",inv.get(currentDisplay).getPrice()) + "\n");
txt.append("DVD Total value: $" + String.format("%.2f",inv.get(currentDisplay).value()) + "\n");
txt.append("Restocking Fee: $" + String.format("%.2f",inv.get(currentDisplay).fee()) + "\n");
txt.append("Total value: $" + String.format("%.2f",inv.value()));
}
/**
*
* @return
*/
public Object getContentPanel() {
return this.getContentPanel();
public DVD_Application gui = new DVD_Application();
gui.pack();
gui.setVisible(true);
}
// I have this final file that is saying I don't have a main method. I have been working all night on my exchange server. I know I can't see the forest for the trees. I am exhausted. When I put the public void string args in I get the "class, interface or enumerator exptected.
Last edited by redhead; 07-12-2009 at 12:20 AM.
Reason: Code tags added
|
| |
07-12-2009, 03:41 PM
|
#12 (permalink)
| | Java fanboy
Join Date: Aug 2003
Posts: 1,227
| The syntax in this file has all sorts of problems. You have large sections of code outside of methods and methods outside of classes You're not going to be get much to work until you fix the syntax problems.
Sorry I can't be much more help. Remember, all methods need to be within the "{" and "}" of the class, and with the exception of variable declarations, all the code should be withing the "{" and "}" of methods. |
| |
07-12-2009, 05:04 PM
|
#13 (permalink)
| | Recruit
Join Date: Jul 2009
Posts: 6
| That's ok. Thank you so much for trying to help. I just need a good week of hammering the basic syntax into my head and then maybe things will click. Your input in this forum is very valuable and I appreciate your time and effort.
Thank you. |
| |
07-12-2009, 05:08 PM
|
#14 (permalink)
| | Java fanboy
Join Date: Aug 2003
Posts: 1,227
| Feel free to stop by with more questions. Once you understand the syntax, things should start falling in place for you. |
| |
07-12-2009, 08:44 PM
|
#15 (permalink)
| | Recruit
Join Date: Jun 2009
Posts: 6
| help im missing an opening bracket and cant find where it needs to go Code: import java.awt.*; // This is real important for the GUI interface....it contains all the classes for creating
//user interfaces and for painting graphics and images.
// good example for showing an image http://www.roseindia.net/java/example/java/awt/AwtImage.shtml
import javax.swing.*; // Allows for the creation of Swing text components with this you can display text and optionally
// allow the user to edit the text...which will be a benefit to us in editing fields in the
// next part.
import java.io.InputStreamReader; // Class to be able to read bytes and convert them into characters
// a good example would be on web page http://www.codeproject.com/KB/java/javabasicsio.aspx
import java.io.IOException; // Class to be able to construct i/o exceptions with a specified cause and detail messages
// good example at http://www.roseindia.net/java/beginners/WriteTextFileExample.shtml
import java.util.*; // The contains collections of framework, legacy collection classes, event model,
// date and time facilities, and miscellaneous utility classes to allow you to reuse code
// for things such as arrays, string tokenizer and random-number generation
import java.text.NumberFormat; // Class that allows for the easy formating of number with such methods as getCurrencyInstance
import java.io.BufferedReader; // Class to be able to read text from a character-input stream
// it buffer characters so as to provide for the efficient reading of character
// arrays and lines...general used with FileReaders adn InputStreamReaders
import java.awt.event.*;
import java.net.URL;
/* The first thing to define here is a class to hold the information for a product.
Notice there is no "public" interface to this class. If we used the word "public"
in front then this class would have to be in a file of its own. Product can only
be used within this program. Additionally notice the word Comparable, that is coming from using
java.util.* collections and will allow us to use sort without defining our own method */
class Product implements Comparable
{ //Remember private variables can only be read locally.
private double prodprice; //Product price
private int numinstock; //Number of product in stock
private String prodname; //Name of the product
private int prodId; //Product id number.
public Product() // Default constructor for the Product
{ // Left blank intentionally....number variables already set to 0 automatically.
}
// Constructor
public Product(int In_ProductNumber, double In_ProductPrice, int In_NumberInStock, String In_ProductName) {
this.prodId = In_ProductNumber;
this.prodprice = In_ProductPrice;
this.numinstock = In_NumberInStock;
this.prodname = In_ProductName;
}
public void set_prodId(int num) // Method to set the Product number
{
prodId = num;
}
public int get_prodId() // Method to get the Product number
{
return prodId;
}
public void set_prodprice(double prod) // Method to set the Price of the product
{
prodprice = prod;
}
public double get_prodprice() // Method to get the Price of the product
{
return prodprice;
}
public void set_numinstock(int numstock) // Method to set the Price of the product
{
numinstock = numstock;
}
public int get_numinstock() // Method to get the Price of the product
{
return numinstock;
}
public void set_prodname(String name) // Method to set the name of the product
{
prodname = name;
}
public String get_prodname() // Method to get the name of the product
{
return prodname;
}
public double calculateValue() // Method to calculate the value of the product inventory
{
return prodprice * numinstock;
}
//Before we created our own sort algorithm and did comparison using string compares.
//There is an easier way using code that is already provided by java called the
//the compareTo method. It is used to implement the Comparable interface which
//allows us to sort an array of Products using Arrays.sort()
//We can define it to compare any part of the array, in this case prodname.
//The trick to this method is that it returns -1, 0, or 1
//depending on if the compared to object should appear before, the same, or after
//the current item.
public int compareTo (Object o)
{
Product p = (Product) o;
return prodname.compareTo(p.get_prodname());
}
// We have been using this to print to the command line and now we
// will use it for error checking when having problems.
// Could have used the values straight out but decided to use the get methods instead.
public String toString()
{
return "Product Number : " + get_prodId() + "\n"
+ "Product Name : " + get_prodname() + "\n"
+ "Number in Stock : " + get_numinstock() + "\n"
+ "Product Price : " + NumberFormat.getCurrencyInstance(Locale.US).format(get_prodprice()) + "\n"
+ "Value : " + NumberFormat.getCurrencyInstance(Locale.US).format(calculateValue());
}
}//end class Product
// Extending the Product Class and to include Bulkproduct
class Bulkproduct extends Product
{ // New attribute of items per carton
private int p_itemsPerCarton;
public Bulkproduct () {
super();
}
//--------Constructor based on product as superclass
public Bulkproduct (int In_ProductNumber, double In_ProductPrice, int In_NumberInStock, String In_ProductName, int in_itemsPerCarton)
{
super(In_ProductNumber, In_ProductPrice, In_NumberInStock, In_ProductName);
p_itemsPerCarton=in_itemsPerCarton;
}
// method calculateValue() returns double of current value
// of unit count with addition 5% restock fee.
public double calculateValue() { return super.calculateValue()*1.05; }
public double get_restockingfee() { return super.get_prodprice()*1.05; }
public int get_itemsPerCarton() { return p_itemsPerCarton; };
public void set_itemsPerCarton( int in_itemsPerCarton ) { if ( in_itemsPerCarton<0 ) p_itemsPerCarton=0-in_itemsPerCarton;
else
p_itemsPerCarton=in_itemsPerCarton;
}
//---------toString method that extends the product toString
public String toString()
{
//---------The call to the super toString allows the capture of the private variables
//----------without having to call the get...methods
return String.format(super.toString()+String.format("\n%s: %d\n",
"Items/Carton",p_itemsPerCarton));
}
}//end clas Bulkproduct
// Class that represents a collection of Bulkproduct objects
class Inventory {
Bulkproduct[] myInventory; // An array of bulk products calling it myInventory
// create an initially empty inventory capable of holding different Bulkproducts
public Inventory( )
{
myInventory = new Bulkproduct[0];
}
// This is an interesting method so that the length of our array
// can in essence be dynamic. It will allow us add a Bulkproduct
// to the end of the inventory. For Part 6 we will need to figure out
// how to do a deleteBulkproduct.
public void setProduct(Product p, int index)
{
inventory[index] = p;
}
public void addBulkproduct(Bulkproduct new_Bulkproduct)
{
// create a new array of Bulkproducts that can hold one more than the current array of Bulkproducts
Bulkproduct[] new_inventory = new Bulkproduct[this.getSize() + 1];
//copy all the old ones to the front of the new array
for (int i = 0; i < this.getSize(); i++) {
new_inventory[i] = myInventory[i];
}
// add the new Bulkproduct to the end of the new array
new_inventory[this.getSize()] = new_Bulkproduct;
// replace the old inventory with the new one
myInventory = new_inventory;
}
// Get the number of Bulkproducts in the inventory
public int getSize()
{
return myInventory.length; //Another feature we have using the java.util.* collections
}
// Get the Bulkproducts at the location index in the inventory
public Bulkproduct getBulkproduct(int index)
{
return myInventory[index];
}
// Add up the value of all products in the array.
public double getTotalValueOfAllInventory()
{
double tot = 0.00;
for(int i = 0; i < getSize(); i++)
{
tot += myInventory[i].calculateValue();
}
return tot;
}
// Well now we are sorting the values in the myInventory
public void sortInventory()
{
Arrays.sort(myInventory);
}
}
// GUI for the Inventory
// Contains an inventory of product
// and lets the user step through them one by one
class InventoryGUI extends JFrame
{
// create inventory for the Office Supplies
private Inventory theInventory;
// index in the inventory of the currently displayed office supply.
// the index starts at 0, goes to the number of Office Supplies in the inventory minus 1
private int index = 0;
// GUI elements to display currently selected Office Supply's information
private final JLabel prodIdLabel = new JLabel("Item Number: ");
private JTextField prodIdText;
private final JLabel prodnameLabel = new JLabel("Product Name: ");
private JTextField prodnameText;
private final JLabel manufacturerLabel = new JLabel("Product Manufacturer: ");
private JTextField itemsPerCartonText;
private final JLabel prodpriceLabel = new JLabel("Price: ");
private JTextField prodpriceText;
private final JLabel numinstockLabel = new JLabel("Number in Stock: ");
private JTextField numinstockText;
private final JLabel valueLabel = new JLabel("Value: ");
private JTextField valueText;
private final JLabel restockingFeeLabel = new JLabel("Restocking Fee: ");
private JTextField restockingFeeText;
private final JLabel totalValueLabel = new JLabel("Inventory Total Value: ");
private JLabel totalValueText;
// setup the buttons in the GUI
// go to the next product in the list
private Action nextAction = new AbstractAction("Next")
{
public void actionPerformed(ActionEvent evt) {
// go forward one product
index++;
// check to see if there is a next product
if ( index == theInventory.getSize() ) {
// if we're at the last product in the list, then we can't go any further forward
// so we wrap around to the beginning
index = 0;
}
repaint();
}
};
private JButton nextButton = new JButton(nextAction);
// go the previous product in the list
private Action previousAction = new AbstractAction("Previous") {
public void actionPerformed(ActionEvent evt) {
index--;
// if the user hits previous at the first product in the list, then loop back to the last product
if (index < 0) {
index = theInventory.getSize() - 1;
}
repaint();
}
};
private JButton previousButton = new JButton(previousAction);
// advance to the first product in the list
private Action firstAction = new AbstractAction("First") {
public void actionPerformed(ActionEvent evt) {
index = 0;
repaint();
}
};
private JButton firstButton = new JButton(firstAction);
// advance to the last product in the list
private Action lastAction = new AbstractAction("Last") {
public void actionPerformed(ActionEvent evt) {
index = theInventory.getSize() - 1;
repaint();
}
};
private JButton lastButton = new JButton(lastAction);
// advance to the add product in the list
private Action addAction = new AbstractAction("ADD") {
public void actionPerformed(ActionEvent evt) {
myInventoryGUI.addBulkproductToInventory( new Bulkproduct( 0, 0.00, 0, "", 0) );;
index = theInventory.getSize() - 1;
repaint();
}
};
private JButton addButton = new JButton(addAction);
// advance to the delete product in the list
private Action deleteAction = new AbstractAction("DELETE") {
public void actionPerformed(ActionEvent evt) {
index = 0;
repaint();
}
};
private JButton deleteButton = new JButton(deleteAction);
// advance to the modify product in the list
private Action modifyAction = new AbstractAction("MODIFY") {
public void actionPerformed(ActionEvent evt) {
if (modifyButton.getText().equals("Modify")) {
modifyButton.setText("Click to Modify!");
// make the fields of the current dvd editable
prodIdText.setEditable(true);
prodnameText.setEditable(true);
itemsPerCartonText.setEditable(true);
prodpriceText.setEditable(true);
numinstockText.setEditable(true);
// the second time,
} else if (modifyButton.getText().equals("Click to Modify!")) {
try {
//Assign the text fields to variables
String prodIdTemp = prodIdText.getText().trim();
//Convert text into int and double.
int prodNumTemp = Integer.parseInt ( prodIdTemp );
Product newProduct = new Product(prodNumTemp, prodnameTemp, itemsPerCartonTemp, prodpriceTemp, numinstockTemp );
ProductInventory2.setProduct(newProduct, index);
} catch (Exception modifyException) {
JOptionPane.showMessageDialog(null, "Error modifying dvd's information:\n" + modifyException);
}
modifyButton.setText("Modify");
prodIdTemp.setEditable(false);
// update the display
repaint();
}
};
private JButton modifyButton = new JButton(modifyAction);
// advance to the save product in the list
private Action saveAction = new AbstractAction("SAVE") {
public void actionPerformed(ActionEvent evt) {
prodIdText.getText().trim();
prodnameText.getText().trim();
itemsPerCartonText.getText().trim();
prodpriceText.getText().trim();
numinstockText.getText().trim();
repaint();
}
};
private JButton saveButton = new JButton(saveAction);
// Add the product to the underlying inventory object
public void addBulkproductToInventory(Bulkproduct temp)
{
theInventory.addBulkproduct(temp);
sortInventory();
repaint();
}
// sort the items in the underlying inventory object
public void sortInventory()
{
theInventory.sortInventory();
repaint();
}
// constructor for the GUI, in charge of creating all GUI elements
public InventoryGUI()
{
// create the inventory object that will hold the product information
theInventory = new Inventory();
// setup the GUI
// add the next button to the top of the GUI
// setup a panel to collect all the buttons in a GridLayout with 1 row and 4 columns
JPanel buttonPanel = new JPanel(new GridLayout(1, 4, 0, 4));
buttonPanel.add(firstButton);
buttonPanel.add(previousButton);
buttonPanel.add(nextButton);
buttonPanel.add(lastButton);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
JPanel buttonPanel2 = new JPanel(new GridLayout(4, 1, 4, 1));
buttonPanel2.add(addButton);
buttonPanel2.add(deleteButton);
buttonPanel2.add(modifyButton);
buttonPanel2.add(saveButton);
getContentPane().add(buttonPanel2, BorderLayout.EAST);
// product information
// setup a panel to collect all the components in a GridLayout with 8 rows and 2 columns.
JPanel centerPanel = new JPanel(new GridLayout(8, 2, 0, 4));
centerPanel.add(prodIdLabel);
prodIdLabel.setBorder(BorderFactory.createEmptyBorder(0,3,0,3));
prodIdText = new JTextField("");
prodIdText.setEditable(false );
centerPanel.add(prodIdText);
centerPanel.add(prodnameLabel);
prodnameLabel.setBorder(BorderFactory.createEmptyBorder(0,3,0,3));
prodnameText = new JTextField("");
prodnameText.setEditable(false);
centerPanel.add(prodnameText);
centerPanel.add(manufacturerLabel);
manufacturerLabel.setBorder(BorderFactory.createEmptyBorder(0,3,0,3));
itemsPerCartonText = new JTextField("");
itemsPerCartonText.setEditable(false);
centerPanel.add(itemsPerCartonText);
centerPanel.add(prodpriceLabel);
prodpriceLabel.setBorder(BorderFactory.createEmptyBorder(0,3,0,3));
prodpriceText = new JTextField("");
prodpriceText.setEditable(false);
centerPanel.add(prodpriceText);
centerPanel.add(numinstockLabel);
numinstockLabel.setBorder(BorderFactory.createEmptyBorder(0,3,0,3));
numinstockText = new JTextField("");
numinstockText.setEditable(false);
centerPanel.add(numinstockText);
centerPanel.add(restockingFeeLabel);
restockingFeeLabel.setBorder(BorderFactory.createEmptyBorder(0,3,0,3));
restockingFeeText = new JTextField("");
restockingFeeText.setEditable(false);
centerPanel.add(restockingFeeText);
centerPanel.add(valueLabel);
valueLabel.setBorder(BorderFactory.createEmptyBorder(0,3,0,3));
valueText = new JTextField("");
valueText.setEditable(false);
centerPanel.add(valueText);
// add the overall inventory information to the panel
centerPanel.add(totalValueLabel);
totalValueLabel.setBorder(BorderFactory.createEmptyBorder(0,3,0,3));
totalValueText = new JLabel("");
centerPanel.add(totalValueText);
// setup the logo for the GUI
URL url = this.getClass().getResource("logo.jpg");
Image img = Toolkit.getDefaultToolkit().getImage(url);
// scale the image so that it'll fit in the GUI
Image scaledImage = img.getScaledInstance(100, 100, Image.SCALE_AREA_AVERAGING);
// create a JLabel with the image as the label's Icon
Icon logoIcon = new ImageIcon(scaledImage);
JLabel companyLogoLabel = new JLabel(logoIcon);
companyLogoLabel.setBorder(BorderFactory.createEmptyBorder(3,3,3,3));
// add the logo to the GUI
getContentPane().add(companyLogoLabel, BorderLayout.WEST);
// add the panel to the center of the GUI's window
getContentPane().add(centerPanel, BorderLayout.CENTER);
}
// Get the GUI to show up on the screen
public void showGUI() {
this.setDefaultCloseOperation( EXIT_ON_CLOSE );
this.pack();
this.setSize(700, 400);
this.setResizable(false);
this.setLocationRelativeTo( null );
this.setVisible(true);
repaint();
}
// repaint the GUI with current product's information
public void repaint() {
Bulkproduct temp = theInventory.getBulkproduct(index);
if (temp != null) {
prodIdText.setText( ""+temp.get_prodId() );
prodnameText.setText( temp.get_prodname() );
itemsPerCartonText.setText( String.format("%d",temp.get_itemsPerCarton()));
prodpriceText.setText( String.format("$%.2f", temp.get_prodprice()) );
restockingFeeText.setText( String.format("$%.2f", temp.get_restockingfee()) );
numinstockText.setText( ""+temp.get_numinstock() );
valueText.setText( String.format("$%.2f", temp.calculateValue() ) );
}
totalValueText.setText( String.format("$%.2f", theInventory.getTotalValueOfAllInventory() ) );
}
} // End InventoryGUI class
// Program that displays the value of products in the inventory.
class InventoryPart5
{
public static void main( String args[] ) throws IOException
{
// create Scanner to obtain input from command window
BufferedReader input = new BufferedReader(new InputStreamReader(System.in) );
//Instantiate a GUI Inventory object
InventoryGUI myInventoryGUI = new InventoryGUI();
// change this to false to do command line input
if ( true ) { /* program not working when set to true for some reason */
System.out.println("Loading\n\n");
myInventoryGUI.addBulkproductToInventory( new Bulkproduct( 1, 9.99, 300, "DVD", 20) );
myInventoryGUI.addBulkproductToInventory( new Bulkproduct( 2, 3.99, 25, "ToothPaste", 15) );
myInventoryGUI.addBulkproductToInventory( new Bulkproduct( 3, 5.99, 33, "Candy Bar", 22) );
myInventoryGUI.addBulkproductToInventory( new Bulkproduct( 4, 10.99, 10, "Ink", 500) );
System.out.println("Done loading\n\n");
} else {
//Print out a screen title
System.out.println("Inventory Program\n\n");
// we're going to keep asking for user input until the user enters stop for an item name
while(true) {
//Instantiate a new Bulkproduct object each time we could get input from the user
Bulkproduct myItem = new Bulkproduct();
System.out.println( "Enter the name of product or the word stop: " ); // prompt for input
myItem.set_prodname(input.readLine());// read item name or stop
// if the user entered stop for the item name, then quit the loop
if ( myItem.get_prodname().equalsIgnoreCase("stop") ) {
break;
}
//Enter Item number
System.out.print( "Enter the Item number: " ); // prompt for input
int prodId = Integer.valueOf(input.readLine()).intValue();
myItem.set_prodId(prodId);// read item number
// while loop to repeat the entry of the item number until a positive value is entered
while (myItem.get_prodId()<=0.0)
{
System.out.println("Wrong Entry");
System.out.println("Please enter a positive Item Number:");
myItem.set_prodId(Integer.valueOf(input.readLine()).intValue()); // read Item number
}
// Enter Number of Items in Stock
System.out.print("Enter number of Items in Stock: ");
myItem.set_numinstock(Integer.valueOf(input.readLine()).intValue()); // read Number of Items in Stock
// while loop to repeat the entry of Items in stock until a positive value is entered
while (myItem.get_numinstock() <= 0.0)
{
System.out.println("Wrong Entry");
System.out.println("Please enter a positive Number in Stock:");
myItem.set_numinstock(Integer.valueOf(input.readLine()).intValue()); // read Item number
}
// Enter price of the Item
System.out.print( "Enter the price of the item: " ); // prompt for input
myItem.set_prodprice(Double.valueOf(input.readLine()).doubleValue()); // Read price of the Bulkproduct
// while loop to repeat the entry of Items in stock until a positive value is entered
while (myItem.get_prodprice()<=0.0)
{
System.out.println("Wrong Entry");
System.out.println("Please enter a positive Item Price:");
myItem.set_prodprice(Double.valueOf(input.readLine()).doubleValue()); // read Item Price
}
// Enter Number of Items in a Package
System.out.print( "Enter the Items / Carton: " ); // prompt for input
myItem.set_prodprice(Double.valueOf(input.readLine()).doubleValue());
// while loop to repeat the entry of items / carton until a postitive value is entered
while (myItem.get_prodprice()<=0.0)
{
System.out.println("Wrong Entry");
System.out.println("Please enter a positive Item Price;");
myItem.set_prodprice(Double.valueOf(input.readLine()).doubleValue());// Read items / carton name of the Bulkproduct
}
System.out.println();
// add the newly created object to the existing inventory
myInventoryGUI.addBulkproductToInventory(myItem);
} // end while
}
// Display the inventory of Bulkproducts on the screen, one Bulkproduct at a time
myInventoryGUI.showGUI();
} // end method main
} // end class InventoryPart5 |
| | | Thread Tools | | | | Display Modes | Linear Mode |
Posting Rules
| You may not post new threads You may not post replies You may not post attachments You may not edit your posts HTML code is Off | | | All times are GMT -8. The time now is 10:18 PM. |
Copyright © 2000-2008, Milano Interactive Web Hosting provided by Portal 360 Web Hosting |  | |