Need help with Class Project!

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #16
    Originally posted by JenniferT
    I am using 1.5 and I just realized what I did wrong (duh). I saved the file as Church.java instead of Churches.java. It still compiled, but I got a run error when it ran. Churches run fine and I see how you are sorting it. I will try to apply this to my program and will post on here if I can't get it.

    I'm sure I'll have more question with the later assignments so I will post on here in the future if that's OK. Or I can create a new post. Whatever is best.
    Just keep posting here as long as it's the same assignment so that those answering do not answer out of context. Make sure you really understand every line in that example (if you don't post here) because that really forms the basis of most programs you are going to write.

    Comment

    • stevedub
      New Member
      • Jan 2007
      • 40

      #17
      Hello all, I have that same exact assingment to do as well, and I am having a rough time to. I've read through many posts about this assignment, but I am just not really comprehending how to set up the array and how to sort. I will try to take a better look at it to see if I can understand it better. Here is my code I have so far by the way:

      Code:
      // Product class
      
      
      public class Product {
      
      	private String title;
      	private double item;
      	private double stock;
      	private double price;
      
      	// Constructor to initialize the product information.
      	public Product(String title, double item, double stock,
      			double price) {
      		setTitle(title);
      		setItem(item);
      		setStock(stock);
      		setPrice(price);
      
      	}
      
      	// Method to get the title
      	public String getTitle() {
      		return title;
      	}
      
      	// Method to get the item number
      	public double getItem() {
      		return item;
      	}
      
      	//Method to get the stock
      	public double getStock() {
      		return stock;
      	}
      
      	//Method to get the price
      	public double getPrice() {
      		return price;
      
      
      
      	}
      
      	// Method to set the title name.
      	public void setTitle(String title) {
      		this.title = title;
      	}
      
      	// Method to set the item number.
      	public void setItem(double item) {
      		this.item = item;
      	}
      
      	// Method to set the stock available.
      	public void setStock(double stock) {
      		this.stock = stock;
      	}
      
      	//Method to set the price.
      	public void setPrice(double price) {
      		this.price = price;
      
      	}
      	// Method to compute the value of inventory.
      	public double getInvValue() {
      		return this.stock *this.price;
      	}
      
      }
      
      
      // Inventory program
      // Main application
      
      
      
      public class Inventory
      {
      	public static void main (String args [])
      	{
      
      	System.out.println ("Inventory of DVD Movies:\n");
      
      		String title = "Beerfest";
      		double item = 1;
      		double stock = 15;
      		double price = 22.50;
      		double value;
      
      	Product product = new Product (title, item, stock, price);
      
      	System.out.printf( "%s%18s\n", "DVD Title:", product.getTitle() );
      
      	System.out.printf( "%s%16s\n", "Item #:", product.getItem() );
      
      	System.out.printf( "%s%8s\n", "Number in Stock:" , product.getStock() );
      
      	System.out.printf( "%s%18s\n", "Price:", product.getPrice() );
      
      
      
      	System.out.printf( "%s%9s\n", "Inventory Value:", product.getInvValue() );
      
      	}
      }

      Comment

      • JenniferT
        New Member
        • Jan 2007
        • 15

        #18
        OK, so I went through and I think I got the sort figured in, but now I can't compile my program. The error I get is:

        C:\Inventory2.j ava:112: illegal start of expression
        public void sortByName() {
        ^
        1 error

        Tool completed with exit code 1

        Why can't I start my expression like that? In the Churches program you did and that compiles fine. What am I missing?

        Comment

        • Ganon11
          Recognized Expert Specialist
          • Oct 2006
          • 3651

          #19
          Originally posted by JenniferT
          OK, so I went through and I think I got the sort figured in, but now I can't compile my program. The error I get is:

          C:\Inventory2.j ava:112: illegal start of expression
          public void sortByName() {
          ^
          1 error

          Tool completed with exit code 1

          Why can't I start my expression like that? In the Churches program you did and that compiles fine. What am I missing?
          That sounds to me like there is something wrong with the previous line of code. Perhaps you forgot a semicolon, or left a set of curly braces {} unclosed.

          Comment

          • JenniferT
            New Member
            • Jan 2007
            • 15

            #20
            Ahh, Sorry! I forgot to post the code.

            Here it is:
            Code:
            //Inventory2.java
            
            
            import java.util.*;
            class Product implements Comparable
            
            {
               private String name; 	// class variable that stores the item name
               private long number;	  // class variable that stores the item number
               private long stockQuantity;   // class variable that stores the quantity in stock
               private double price;	  // class variable that stores the item price
            
               public Product() // Constructor for the Product class
               {
            	  name = "";
            	  number = 0L;
            	  stockQuantity = 0L;
            	  price = 0.0;
               }
               public Product(String name, long number, long stockQuantity, double price) // Constructor for the Supplies class
            	  {
                  this.name = name;
            	  this.number = number;
            	  this.stockQuantity = stockQuantity;
            	  this.price = price;
               	  }
            
               public void setItemName(String name)  // Method to set the item name
               {
            	  this.name = name;
               }
               public String getItemName()  // Method to get the item name
               {
            	  return name;
               }
            
            
               public void setItemNumber(long number)  // Method to set the item number
               {
            	  this.number = number;
               }
               public long getItemNumber()  // Method to get the item number
               {
            	  return number;
               }
            
            
               public void setStockQuantity(long quantity)  // Method to set the quantity in stock
               {
            	  stockQuantity = quantity;
               }
               public long getStockQuantity()  // Method to get the quantity in stock
               {
            	  return stockQuantity;
               }
            
            
               public void setItemPrice(double price)  // Method to set the item price
               {
            	  this.price = price;
               }
               public double getItemPrice()  // Method to get the item price
               {
            	  return price;
               }
            
            
               public double calculateInventoryValue()  // Method to calculate the value of the inventory
               {
            	  return price * stockQuantity;
               }
               public int compareTo (Object o)
               {
            
            
               Product p = (Product)o;
            	  return name.compareTo(p.getItemName());
               }
            
               public String toString()
               {
            	  return "DVD Title: "+name + "\nNumber: "+number+"\nPrice: $"+price+"\nQuantity: "+stockQuantity + "\nValue: $"+calculateInventoryValue();
               }
            
            
            }//end class Product
            
            public class Inventory2
            {
               // main methods begins execution of java application
               public static void main( String args[])
               {
            
               Product[] supplies = new Product[3];
            
               Product p1 = new Product("cDVD3", 1, 11, 10.99);
               Product p2 = new Product("aDVD2", 2, 22, 20.99);
               Product p3 = new Product("bDVD1", 3, 33, 30.99);
            
               supplies[0] = p1;
               supplies[1] = p2;
               supplies[2] = p3;
            
             //  product temp[] supplies = new product[1];
            
            
            
            //OLD CODE-------------------------------------
             //Arrays.sort(supplies);
            //
            //
             public void sortByName() {
             }
             public String toString() {
              String s = "";
              for(Product p : supplies) {
               s = s + p.toString();
               s = s + "\n\n";
              }
              return s;
             }
             public void addProduct(Product p1) {
              Product[] p = supplies;
              Product[] temp = new Product[p.length + 1];
              for(int i = 0; i < p.length; i++) {
               temp[i] = p[i];
              }
              temp[(temp.length - 1)] = p1;
              supplies = temp;
             }
            
            //
            //
            
            
            //END OLD CODE------------------------------------
            
            
            	//sorting the array using Bubble Sort
               double total = 0.0;
            
               for(int i= 0; i < 3;i++)
               {
               total = total + supplies[i].calculateInventoryValue();
               }
            
            
            
                  for(Product p: supplies)
                  {
                  System.out.println(p);
                  System.out.println();
                }
            
            
            
                for(Product p: supplies)
                {
                System.out.println(p);
                System.out.println();
                }
            
            
               System.out.println("Total Value is: $"+total);
            
            
               } // end main method
            }//end class Inventory2

            Comment

            • stevedub
              New Member
              • Jan 2007
              • 40

              #21
              Were you able to get the sorting down yet Jennifer? I just don't understand the concept of how to code in a sort. I have looked at numerous examples, but it just doesnt' seem to click

              Comment

              • JenniferT
                New Member
                • Jan 2007
                • 15

                #22
                A little bit. The code from earlier in this post was a good example. I am stuck though as to why I can't my current code to compile.

                Comment

                • r035198x
                  MVP
                  • Sep 2006
                  • 13225

                  #23
                  Code:
                  //Inventory2.java
                  
                  
                  import java.util.*;
                  class Product implements Comparable {
                  	private String name; 	// class variable that stores the item name
                      private long number;	  // class variable that stores the item number
                      private long stockQuantity;   // class variable that stores the quantity in stock
                      private double price;	  // class variable that stores the item price
                  
                      public Product() {
                  		name = "";
                  	    number = 0L;
                  	    stockQuantity = 0L;
                  	    price = 0.0;
                      }
                  
                      public Product(String name, long number, long stockQuantity, double price) {
                  		this.name = name;
                  	    this.number = number;
                  	    this.stockQuantity = stockQuantity;
                  	    this.price = price;
                     	}
                  
                     	public void setItemName(String name) {
                  		this.name = name;
                      }
                  
                      public String getItemName() {
                  		return name;
                      }
                  
                      public void setItemNumber(long number) {
                  		this.number = number;
                      }
                  
                      public long getItemNumber() {
                  		return number;
                      }
                  
                      public void setStockQuantity(long quantity) {
                  		stockQuantity = quantity;
                      }
                  
                      public long getStockQuantity() {
                  		return stockQuantity;
                      }
                  
                      public void setItemPrice(double price) {
                  		this.price = price;
                      }
                  
                      public double getItemPrice() {
                  		return price;
                      }
                  
                      public double calculateInventoryValue() {
                  		return price * stockQuantity;
                      }
                  
                      public int compareTo (Object o) {
                  		Product p = null;
                  		try {
                  			p = (Product)o;
                  		}
                  		catch(ClassCastException cE) {
                  			cE.printStackTrace();
                  		}
                  		return name.compareTo(p.getItemName());
                  	}
                  
                  	public String toString() {
                  		return "DVD Title: "+name + "\nNumber: "+number+"\nPrice: $"+price+"\nQuantity: "+stockQuantity + "\nValue: $"+calculateInventoryValue();
                  	}
                  }
                  
                  public class Inventory2 {
                  	Product[] supplies;
                  
                  	public static void main(String[] args) {
                  		Inventory2 inventory = new Inventory2();
                  	    inventory.addProduct(new Product("cDVD3", 1, 11, 10.99));
                  	    inventory.addProduct(new Product("aDVD2", 2, 22, 20.99));
                  	    inventory.addProduct(new Product("bDVD1", 3, 33, 30.99));
                  
                  	    double total = inventory.calculateTotalInventory();
                  
                  	    System.out.println("Total Value is: $"+total);
                  
                  		System.out.println("*****Before Sorting******");
                  	    inventory.showInventory();
                  	    inventory.sortByName();
                  	    System.out.println("*****After Sorting By Name******");
                  	    inventory.showInventory();
                  
                  	}
                  
                      public void sortByName() {
                  		for (int i = 1; i < supplies.length; i++) {
                  			int j;
                  			Product val = supplies[i];
                  			for (j = i-1; j > -1; j--) {
                  				Product temp = supplies[j];
                  				if (temp.compareTo(val) <= 0) {
                  					break;
                  				}
                  				supplies[j+1] = temp;
                  			}
                  			supplies[j+1] = val;
                  		}
                      }
                  
                      //creates a String representation of the array of products
                   	public String toString() {
                  		String s = "";
                    		for(Product p : supplies) {
                     			s = s + p.toString();
                     			s = s + "\n\n";
                    		}
                    		return s;
                  	}
                  
                  	//Using an array so adding an item requires us to increase the size of the array first
                  	public void addProduct(Product p1) {
                  		if(supplies == null) {
                  			supplies = new Product[0];
                  		}
                  		Product[] p = supplies; //Copy all products into p first
                    	 	Product[] temp = new Product[p.length + 1]; //create bigger array
                       	for(int i = 0; i < p.length; i++) {
                  	    	temp[i] = p[i];
                    	 	}
                    	 	temp[(temp.length - 1)] = p1; //add the new product at the last position
                       	supplies = temp;
                  	}
                  
                  	//sorting the array using Bubble Sort
                  	public double calculateTotalInventory () {
                  		double total = 0.0;
                     		for(int i = 0; i < supplies.length;i++) {
                  			total = total + supplies[i].calculateInventoryValue();
                  		}
                  		return total;
                  	}
                  
                  	public void showInventory () {
                  		System.out.println(toString()); //call our toString method
                      }
                  }
                  You really should ask about anything at all that you are unsure about here.

                  Comment

                  • stevedub
                    New Member
                    • Jan 2007
                    • 40

                    #24
                    Ok, I understand the beginning of the code but here is where I start to get confused:
                    Code:
                    public int compareTo (Object o) {
                    Then I get confused when calling the sort in the main app. I guess everything just seems confusing because our text doesn't cover any of this at all. I will try to read the code thourghouly today to see if I can make any sense of it. Thanks for all the great help, you really know your stuff. By the way, how long did it take you to become good with Java?

                    Comment

                    • r035198x
                      MVP
                      • Sep 2006
                      • 13225

                      #25
                      Originally posted by stevedub
                      Ok, I understand the beginning of the code but here is where I start to get confused:
                      Code:
                      public int compareTo (Object o) {
                      Then I get confused when calling the sort in the main app. I guess everything just seems confusing because our text doesn't cover any of this at all. I will try to read the code thourghouly today to see if I can make any sense of it. Thanks for all the great help, you really know your stuff. By the way, how long did it take you to become good with Java?
                      I'm not yet good. I've known Java for about 2,5 yrs now.

                      Now for that compareTo line:

                      When we have integers or any other primitive types, comparing then is pretty straight forward. Just if a == b or if a > b will do just fine.
                      Now we have products of the Product class which is made up of name, code, quantity e.t.c. So what do we mean when we say if(a == b) where a and b are products?
                      Do we mean if they have the same name or the same code or both? That is the point of the compareTo method. It tells us how to compare our products. In the churches example I put two compareTo methods for comparing the objects differently.

                      Now we can compare the products using the compareTo method. This helps us in sorting the products because then we need to know if a product comes before or after a given product. Do you understand this?

                      Comment

                      • stevedub
                        New Member
                        • Jan 2007
                        • 40

                        #26
                        Ok, I understand what you are saying, and I understand the reason for, but I just don't understand the actual code. It's hard to keep all the code straight, then on top of that make sure it compiles. Thanks again for the replies, I'm sure I will have more questions for this Sunday's assignment. The part about adding a subclass, then adding the restocking fee.

                        Comment

                        • JenniferT
                          New Member
                          • Jan 2007
                          • 15

                          #27
                          Thanks r035198x! That makes a lot more sense now and I see what I did wrong with the sort. Now I have to modify the program again.
                          CheckPoint: Inventory Program Part 3

                          Resources Required

                          Chapters 9 & 10 in Java: How to Program

                          • Modify the Inventory Program by creating a subclass of the product class that uses one additional unique feature of the product you chose (for the DVDs subclass, you could use movie title, for example). In the subclass, create a method to calculate the value of the inventory of a product with the same name as the method previously created for the product class. The subclass method should also add a 5% restocking fee to the value of the inventory of that product.

                          • Modify the output to display this additional feature you have chosen and the restocking fee.

                          Compile and run the Java program.

                          I'm not sure where I can add the subclass. I know I could easily add another line of data in the array to include DVD rating for example, but it sounds like that's not what they want. And the 5% should be added by taking the price of the DVD and multiplying by.05 to get the restock fee. This I should be able to add to the current array, correct?

                          Really, thank you so much for all your help - I really appreciate it! :)

                          Comment

                          • JenniferT
                            New Member
                            • Jan 2007
                            • 15

                            #28
                            Here is some code I'm trying to understand:
                            Code:
                            //Inventory3
                            
                            
                            // the DVD Class
                            
                            class DVD extends Inventory {
                            
                            	String genre;					// Genre of the DVD
                            	double restockingFee;			// percentage that is added to the base price as a restocking fee
                            									//( actual inventory value will be the base inventory value plus
                            									// the base inventory value times this amount ) (value + (value * restockFee))
                            
                            	public DVD(String genre, double restockingFee, String Item_Number, String Item_Name, int Items_in_Stock,
                            			double Item_Price) {
                            		super(Item_Number, Item_Name, Items_in_Stock, Item_Price);
                            		this.genre = genre;
                            		this.restockingFee = restockingFee;
                            
                            
                            		// TODO Auto-generated constructor stub
                            	}
                            
                            	//returns the value of the inventory, plus the restocking fee
                            	public double getInventoryValue() {
                            		// TODO Auto-generated method stub
                            		return  super.getInventoryValue() + (super.getInventoryValue() * restockingFee);
                            	}
                            
                            	public String toString()
                            	{
                            		StringBuffer sb = new StringBuffer("Genre      \t").append(genre).append("\n");
                            		sb.append(super.toString());
                            
                            		return sb.toString();
                            	}
                            
                            }
                            
                            //
                            //
                            //
                            
                            //The Inventory class
                            
                            public class Inventory {
                            
                            	String productnumber;
                            
                            	String name;
                            
                            	int numberofunits;
                            
                            	double priceperunit;
                            
                            	// Create a new instance of Inventory
                            	// main constructor for the class
                            	public Inventory(String Item_Number, String Item_Name, int Items_in_Stock,
                            			double Item_Price) {
                            		productnumber = Item_Number;
                            		name = Item_Name;
                            		numberofunits = Items_in_Stock;
                            		priceperunit = Item_Price;
                            	}
                            
                            	public void setItemName(String Item_Name)
                            	// sets the items name
                            	{
                            		name = Item_Name;
                            	}
                            
                            	public void setItemNumber(String Item_Number) { // Sets the Product =Number
                            													// for the item
                            
                            		productnumber = Item_Number;
                            	}
                            
                            	public void setItemsInStock(int Items_in_Stock) { // sets the =number of
                            														// units in stock
                            
                            		numberofunits = Items_in_Stock;
                            	}
                            
                            	public void setItemPrice(double Item_Price) { // sets the price of =the
                            													// item
                            		priceperunit = Item_Price;
                            	}
                            
                            	public String getItemName() { // returns the Product Name of this item
                            		return name;
                            	}
                            
                            	public String getItemNumber() { // returns the Product Number of the =item
                            
                            		return productnumber;
                            	}
                            
                            	public int getItemsInStock() { // returns how many units are in stock
                            		return numberofunits;
                            	}
                            
                            	public double getItemPrice() { // returns the price of the item
                            		return priceperunit;
                            	}
                            
                            	public double getInventoryValue() { // returns the total value of =the stock
                            										// for this item
                            		return priceperunit * numberofunits;
                            	}
                            
                            	public static double getTotalValueOfAllInventory(Inventory [] inv)
                            	{
                            		double tot = 0.0;
                            
                            		for(int i = 0; i < inv.length; i++)
                            		{
                            			tot += inv[i].getInventoryValue();
                            		}
                            		return tot;
                            
                            	}
                            
                            
                            
                            	public String toString()
                            	{
                            		StringBuffer sb = new StringBuffer();
                            
                            		sb.append("DVD Title:      \t").append(name).append("\n");
                            		sb.append("Item #:    	   \t").append(productnumber).append("\n");
                            		sb.append("Number in stock:\t").append(numberofunits).append("\n");
                            		sb.append("Price:          \t").append(String.format("$%.2f%n", priceperunit));
                            		sb.append("Inventory Value:\t").append(String.format("$%.2f%n", this.getInventoryValue()));
                            
                            		return sb.toString();
                            	}
                            
                            
                            }
                            
                            //
                            //
                            //
                            
                            //
                            //
                            //The InvTest Class
                            class InvTest
                            
                            {
                            
                            	public static void main(String args[])
                            
                            	{
                            
                            		double restockFee = 0.05;
                            		// initialize a new inventory object
                            		DVD[] inventory = new DVD[4];
                            
                            		inventory[0] = new DVD("Action" ,restockFee, "00623","aDVD1" , 10, 20.00);
                            		inventory[1] = new DVD("Action" ,restockFee, "00564","dDVD2" , 10,  12.00);
                            		inventory[2] = new DVD("Comedy",restockFee, "00222","cDVD3", 10,  15.00);
                            		inventory[3] = new DVD("Family",restockFee,"00153","bDVD4" , 10, 18.00);
                            
                            
                            		DVD temp[] = new DVD[1];
                            
                            //		sorting the array using Bubble Sort
                            		for(int j = 0; j < inventory.length - 1; j++)
                            		{
                            
                            		    for(int k = 0; k < inventory.length - 1; k++)
                            		    {
                            
                            		        if(inventory[k].getItemName().compareToIgnoreCase(inventory[k+1].getItemName()) > 0)
                            		        {
                            
                            		            temp[0] = inventory[k];
                            		            inventory[k] = inventory[k+1];
                            		            inventory[k+1] = temp[0];
                            
                            		        }//end if
                            
                            		    }//end for loop
                            
                            		}//end for loop
                            
                            
                            		// print the inventory information
                            		for(int j = 0; j < inventory.length; j++)
                            		{
                            			System.out.println(inventory[j].toString());
                            		}
                            
                            
                            		System.out.printf("Total value of all inventory = $%.2f" , Inventory.getTotalValueOfAllInventory(inventory));
                            		return;
                            
                            	}
                            }
                            It works when the 3 classes - DVD, Inventory, InvTest are in separate java files and declared as public, but it doesn't work when I try to combine them and only declare Inventory as public. And it only works when I run the InvTest.java application. It doesn't work if I try to run all 3 separate. I wanted to combine them as I think they should be all in 1 java file to compile and run. Does that make sense?

                            Comment

                            • JenniferT
                              New Member
                              • Jan 2007
                              • 15

                              #29
                              Ahh, I did it again! I just answered my own question. If I declare the InvTest as public and save it as InvTest.java it works. OK, let me analyze and apply it to the program I'm working on.

                              But can anyone answer why it can't be Inventory.java if the Inventory class is declared as public?

                              Comment

                              • stevedub
                                New Member
                                • Jan 2007
                                • 40

                                #30
                                I believe the reason is because you can only have one main class, which is why you declare it public static void main. Let's keep this thread going Jennifer, I'm sure we will really need help for the next assignments, especially with the GUI part of the program.

                                Comment

                                Working...