I am new to programming and have a question regarding a homework assignment. First off this is for an Inventory Program and it is part 2. The assignment is as follows:

Modify the Inventory 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 of each unit, and the value of the inventory of that product. In addition, the output should display the value of the entire inventory.

I have the code written with the exception of creating a method to calculate the total inventory. My issue is that I do not completely understand how to sort the array by name. I have inserted the method and it compiles but it does not sort. I know that I must be missing a line of code somewhere but I am unsure where. Any guidance would be greatly appreciated.

import java.util.Arrays;

public class Inventory1 //declares public class inventory

{

    public static void main(String args []) //starts the program
    {
        
      DVD[] dvd = new DVD[3];
        
                       
        dvd[0] = new DVD( 1, "Knocked Up", 2, 17.99 );//declares a new item number, dvd title, quantity, and price
        

        dvd[1] = new DVD( 2, "Napolean Dynamite", 4, 14.99 );
        

        dvd[2] = new DVD( 3, "Happy Gilmore", 6, 9.99 );
        
	for(int i = 0; i < 3; i++)         

        
           {  
               
               System.out.println(dvd[i]);
               System.out.println();  
              
               System.out.println("The item number is " + dvd[i].getItemNumber());               
               System.out.println("Product Title is " + dvd[i].getDvdTitle()); 
               System.out.println("The number of units in stock is " + dvd[i].getOnHand());
               System.out.println("The price of each DVD is " + dvd[i].getDvdCost());
               System.out.println("The value of the inventory is " + dvd[i].value());  

           } 
        
         
        
     }//end main

} // end class Inventory1
   

class DVD //declares class inventory

{

    
    private int itemNumber;// declares item number as in
    private String dvdTitle;// declares dvd title as string
    private int onHand; // declares on hand as int
    private double dvdCost;// declares cost as double

    public DVD(int stockNumber, String title, int inStock, double price) //constructor
   {
        itemNumber = stockNumber;//intitiates stock number, title, instock, and price
        dvdTitle = title;
        onHand = inStock;
        dvdCost  = price;
    
   } //

    // set DVD StockNumber //sets stock number
    public void setItemNumber(int stockNumber) 

    {
        itemNumber = stockNumber;
    
    } 

    
    public int getItemNumber() // class item number

    {
        return itemNumber; // returns item number
    } //end method get Dvd Item

    
    public void setDvdTitle(String title) //set DVD Title

    {
        dvdTitle = title;
    } 

    public String getDvdTitle() //gets and returns DVD Title

    {
        return dvdTitle;
    } 

    public void setOnHand(int inStock) //Set on hand 

    {
        onHand = inStock;
    } 

    
    public int getOnHand() //gets and returns on hand

    {
        return onHand;
    } //

    public void setDvdCost(double price) // sets dvd cost

    {
        dvdCost = price;
    } 

    
    public double getDvdCost() //gets and returns DVD cost

    {
        return dvdCost;
    } 

    
    public double value() //calculates the value of stock 

    {
        return dvdCost * onHand;
    } 

public DVD[] SortDVD (DVD[] theDVD)
 {
  DVD tmp;
  for (int index = 0; index < theDVD.length; index++)
  {
   for (int anotherindex = index + 1; anotherindex< theDVD.length; anotherindex++)
   {
    String s1 = theDVD[index].getDvdTitle();
    String s2 = theDVD[anotherindex].getDvdTitle();
    if( s1.compareTo(s2) > 0)
    {
     tmp = theDVD[index];
     theDVD[index] = theDVD[anotherindex];
     theDVD [anotherindex] = tmp;
    }
   }
  }
   return theDVD;
  }  
    
} //end class DVD

This might sound knitpicky, but you have a method that sorts an array of DVD objects inside a DVD object. Objects are supposed to have attributes of things they represent in real life. DVDs don't sort other DVDS, that seems like a job the inventory object would do. It makes your program much more functional and easier to work with too.

This is your sort method below:

public DVD[] SortDVD (DVD[] theDVD)
 {
  DVD tmp;
  for (int index = 0; index < theDVD.length; index++)
  {
   for (int anotherindex = index + 1; anotherindex< theDVD.length; anotherindex++)
   {
    String s1 = theDVD[index].getDvdTitle();
    String s2 = theDVD[anotherindex].getDvdTitle();
    if( s1.compareTo(s2) > 0)
    {
     tmp = theDVD[index];
     theDVD[index] = theDVD[anotherindex];
     theDVD [anotherindex] = tmp;
    }
   }
  }
   return theDVD;

For being new to programming you were pretty close to the mark! The type of sort you're using is called a bubble sort. It isn't the fastest sort, but it does get the job done. This is a basic template of how it should look and work:

for (int x =0; x < array.length -1; x++) { 
     if (array[x] > array[x+1]) { 
     temp = array[x]; 
     array[x] = array[x+1]; 
     array[x+1] = temp; 
     x =-1; 
     } 
} 
//x will equal negative one because as soon the code loops it gets incremented to 0

0 1 7 5 3 - the array to sort. The current number that array[x] equals will be represented with an x above it.

x
0 1 7 5 3

--x
0 1 7 5 3

----x
0 1 7 5 3

x
0 1 5 7 3

--x
0 1 5 7 3

----x
0 1 5 7 3

------x
0 1 5 7 3

x
0 1 5 3 7

--x
0 1 5 3 7

----x
0 1 5 3 7

x
0 1 3 5 7

--x
0 1 3 5 7

----x
0 1 3 5 7

------x
0 1 3 5 7

---------x
0 1 3 5 7

Done.

Since you're using letters instead of numbers you would use the .charAt(0) method. .charAt(0) works differently from .compareto, the method you chose to use. .compareto probably doesn't work the way you think it does. Every letter has an ascii value, or a number associated with it. .compareto adds together the ascii values of each letter in each word and subtracts the totals. If the words are different sizes it does not become a reliable way of testing the alphabetical order of words. To get around that you compare each letter individually.

You also want to compare each letter on the same case, meaning either all lower case or all upper case. This is because the value of a lower case letter is different from an upper case letter. To do this you want to use the .tolowercase() or the .touppercase() function.

Your sort function with all the changes applied should look like this:

public void SortDVD(DVD[] theDVD) {
		for (int index = 0; index < theDVD.length - 1; index++) {
			String s1 = theDVD[index].getDvdTitle();
			String s2 = theDVD[index + 1].getDvdTitle();
			if (comparewords(s1, s2)) {
				DVD temp = theDVD[index];
				theDVD[index] = theDVD[index + 1];
				theDVD[index + 1] = temp;
				index = -1;
			}
		}
	}

This only sorts by the first letter, however. If you want to sort by more than the first letter you would want to have a separate compare method that looks kind of like this:

private boolean comparewords(String s1, String s2) {
		boolean islarger = false;

		for (int index = 0; index < s1.length(); index++) {
			if (index < s2.length()) {
				if (s1.toLowerCase().charAt(index) > s2.toLowerCase().charAt(index)) {
					islarger = true;
					break;
				}
				if (s1.toLowerCase().charAt(index) < s2.toLowerCase().charAt(index)) {
					
					break;
				}
			}else { 
				return true; 
			}
		}

		return islarger;
	}

Basically there is a loop, where the integer index is incremented. index represents the index of s1. the method uses the following logic:

- if the two letters being compared are the same, continue

- if the first letter is bigger than the second letter, return true

- if the first letter is less than the second letter, return false

- if the letters are all the same but the second word is smaller than the first word, return true

Your code should look like this if you made all the changes above:

import java.util.Arrays;

public class Inventory1 // declares public class inventory

{

	public static void main(String args[]) // starts the program
	{

		DVD[] dvd = new DVD[3];

		dvd[0] = new DVD(1, "Knocked Up", 2, 17.99);// declares a new item
		// number, dvd title,
		// quantity, and price

		dvd[1] = new DVD(2, "Napolean Dynamite", 4, 14.99);

		dvd[2] = new DVD(3, "Happy Gilmore", 6, 9.99);

//added changes ---------------------------------------------------------
		Inventory1 x = new Inventory1();
		x.SortDVD(dvd);

	}// end main

	public void SortDVD(DVD[] theDVD) {
		for (int index = 0; index < theDVD.length - 1; index++) {
			String s1 = theDVD[index].getDvdTitle();
			String s2 = theDVD[index + 1].getDvdTitle();
			if (comparewords(s1, s2)) {
				DVD temp = theDVD[index];
				theDVD[index] = theDVD[index + 1];
				theDVD[index + 1] = temp;
				index = -1;
			}
		}
	}

	private boolean comparewords(String s1, String s2) {
		boolean islarger = false;

		for (int index = 0; index < s1.length(); index++) {
			if (index < s2.length()) {
				if (s1.toLowerCase().charAt(index) > s2.toLowerCase().charAt(index)) {
					islarger = true;
					break;
				}
				if (s1.toLowerCase().charAt(index) < s2.toLowerCase().charAt(index)) {
					
					break;
				}
			}else { 
				return true; 
			}
		}

		return islarger;
	}
//end of changes --------------------------------------------------------

} // end class Inventory1

class DVD // declares class inventory

{

	private int itemNumber;// declares item number as in
	private String dvdTitle;// declares dvd title as string
	private int onHand; // declares on hand as int
	private double dvdCost;// declares cost as double

	public DVD(int stockNumber, String title, int inStock, double price) // constructor
	{
		itemNumber = stockNumber;// intitiates stock number, title, instock, and
		// price
		dvdTitle = title;
		onHand = inStock;
		dvdCost = price;

	} //

	// set DVD StockNumber //sets stock number
	public void setItemNumber(int stockNumber)

	{
		itemNumber = stockNumber;

	}

	public int getItemNumber() // class item number

	{
		return itemNumber; // returns item number
	} // end method get Dvd Item

	public void setDvdTitle(String title) // set DVD Title

	{
		dvdTitle = title;
	}

	public String getDvdTitle() // gets and returns DVD Title

	{
		return dvdTitle;
	}

	public void setOnHand(int inStock) // Set on hand

	{
		onHand = inStock;
	}

	public int getOnHand() // gets and returns on hand

	{
		return onHand;
	} //

	public void setDvdCost(double price) // sets dvd cost

	{
		dvdCost = price;
	}

	public double getDvdCost() // gets and returns DVD cost

	{
		return dvdCost;
	}

	public double value() // calculates the value of stock

	{
		return dvdCost * onHand;
	}

} // end class DVD

your program will now sort the dvds by alphabetical order!

Thank you for your help, I now have the program compiled and it works as intended. The only thing I do not exactly understand is when the program runs after each element thier is some text DVD@42e816. I read that I have to override the toString so I am working on that. Also youe saud there was a faster way to sort the problem could you tell me what that is or just give me an example.

Again thank you for your help it is greatly appreciated. So far in this class I have not had a proble, understanding the logic behind everything its once I have to sit down and write the code that I begin to get confused.

There are several methods for sorting information, all of which have their strengths and weaknesses.

Bubblesort, the one you have used, is the easiest but the most inefficient.

Another one is:
Selection Sort

void selectionSort(int[] array){
    for (int index = 0; index < array.length - 1; index++) {
        int min = index;
        for (int j = index + 1; j < array.length; j++) {
            if (a[j] < a[min]) {
                min = j;
            }
        }
        int swap = array[index];
        array[index] = a[min];
        array[min] = swap;
    }
}

The selection sort follows the following steps:

1.) starts at index 0 of the array of data
2.) finds the smallest or largest number in the list
3.) swaps the value at index 0 with that number
4.) increase the index by one
5.) repeat

Other sorts you might want to look up are the insertion sort and the quick sort. The fastest would be the quick sort (usually), while the insertion sort never changes speed. Wikipedia has a lot of information on all these sorts as well as the actual code for them.

The @(numbers) are the memory addresses of the objects. That is what the default print does.

Thank you for the explanation. I have just one last question. I am having trouble trying to figure out how to add the total values of each element so that I can print the value of the total inventory.
I know I must use a for loop that will look similar to the

for ( int counter = 0; counter < dvd.length; counter++ )
value += dvd[ counter ];

But I am unsure how to call the value to sum from each element?

double total = 0;
( int counter = 0; counter < dvd.length; counter++ )
total += dvd[ counter ].value();

Every dvd object has a method called value(). This method (the one you created) returns the value of each dvd.

dvd[] looks kind of like this:

index-----object
0 ---------- dvd
1 ---------- dvd
2 ---------- dvd

dvd[counter] is just referencing one of the three dvd objects above, so you'll be able to call every public method that the class dvd has.

Thank you very much for all your help. I have got the program running as intended. The first part of the class I was able to get up and running but the last half is alot harder, I am sure I will be back looking for more. Thanks again.

This question has already been answered. Start a new discussion instead.