Of course I have to make things difficult. If I just put 5 cd names in to an array it would not be that hard to set up a sort for them, and get them in alphabetical order, but I have to have the user enter the names in, so we do not know the names to be used in the sort until after the loop is entered.
Either I do not understand the sorting inside Java, or am just too inexperienced to code it correctly.
Here are my two classes:

import java.util.Scanner; //uses class Scanner

public class Inventory
{// begin class Inventory
	public static void main(String[] args)	
	{//begin method main
	
	
	// create cd Array
	Compactdisk[] cds = new Compactdisk[5];
	[B]Arrays.sort(cds); [/B]
 
	
	cds[0] = new Compactdisk(); // adds to array
	cds[0].getName();
	cds[0].getPrice();
	cds[0].getItemno();
	cds[0].getNstock();
	
	int cdCount = 0;
	float totalValue = 0;
	
	Scanner input = new Scanner(System.in);  // create scanner
	
	
	
			// begin display method
			System.out.print("Enter up to 5 CD Names or STOP to Exit: ");
			String nameInput = input.next(); //read cd name
						
			
		  	while (!nameInput.equalsIgnoreCase("STOP"))
			{// begin main While
			
				cds[cdCount] = new Compactdisk();
				cds[cdCount].setName(nameInput);

				System.out.print("Enter Price of this CD: "); // prompt for price
				cds[cdCount].setPrice(input.nextFloat());	// price input from user.
				while (cds[cdCount].getPrice()<= 0)
				{// begin while
				System.out.print("Price Must Be Greater Than Zero. Enter Price: ");
				cds[cdCount].setPrice(input.nextFloat()); // cd price loop from user.
				} // End while
		
				System.out.print("Enter CD Item Number: "); // prompt for cd item number
				cds[cdCount].setItemno(input.nextInt()); // cds item number input from user
		
				System.out.print("Enter Number of these CDs in Stock: "); // prompt for cd stock
				cds[cdCount].setNstock(input.nextInt()); // cds in stock input from user
				
				        
				System.out.print("CD "+cds[cdCount].getName()+", Item Number "+cds[cdCount].getItemno()+","); // display name
				System.out.printf(" is worth %c%.2f.\n", '$', cds[cdCount].getPrice()); // display individual price
				System.out.printf("We have %d copies in stock, making our inventory for this cd worth %c%.2f\n", cds[cdCount].getNstock(), '$', cds[cdCount].getValue()); //inventory value
				
				try
				{
				totalValue = totalValue + cds[cdCount].getValue();
				}
				
				catch(NullPointerException npe)
				{
				
				} // handles exception
				
				cdCount++;
				
				System.out.printf("Combined Inventory for all CDs is Worth %c%.2f.\n", '$', totalValue);
				System.out.print("Enter up to 5 CD Names or STOP to Exit: "); // internal loop prompt
				nameInput = input.next(); //name input from user
																
			} // End main While
			
			
	
		System.out.print("Ending Program.");
	

	}// end method main
} // end class Payroll

I am getting a "cannot find symbol" error on the arrays.sort line bolded above. I did not expect errors until I started trying to sort on the actual name inside the array. Now I am really in over my head. I have never done sorting before, and wish I had done a much simpler array for my first time. This simple weekend project has turned in to a real bear.
Here is my other class just for clarity.

public class Compactdisk
{// begin class

	//InventoryCD class has 5 fields
	String Name; //  Name of cd
	float price; // price of cd
	int itemno; // item number of cd
	int nstock; // how many units in stock	
	int cdCount; // cd counter for array
	float value; // value for single cd inventory

	
	//Compact disk class constructor
	public Compactdisk()
	
		// 4 fields need to be set up
		{ 
		Name = "";
		price = 0;
		itemno = 0;
		nstock = 0;
		cdCount = 0;
		value = 0;
			}
		
		// set values
	   public void setName(String diskName)
	   {
	   Name = diskName;
	   }
		public void setPrice(float cdPrice)
	   {
	   price = cdPrice;
	   }
		public void setItemno(int cdItemno)
	   {
	   itemno = cdItemno;
	   }
		 public void setNstock(int cdStock)
	   {
	   nstock = cdStock;
	   }
		public void setValue(float cdValue)
		{
		value = cdValue;
		}
		public void setcdCount(int Count)
		{
		cdCount = Count;
		}
	
		
	   // return values
		public String getName()
		{	
		return (Name);
		}
		public float getPrice()
		{	
		return (price);
		}
		public int getItemno()
		{	
		return (itemno);
		}
		public int getNstock()
		{	
		return (nstock);
		}
	
					
		// returns indivudual inventory value for a disk
	   public float getValue()
	   {
	   return(price * nstock);
	   }
		
			
			
		
			
}// end class

Any help on setting up a sort this way would be so much appreciated. I am going to feel like I have lost a weekend for nothing if I cannot get this set up by the time I get back to work in the morning.
Thanks guys.

Well, I have kicked around several things, and after calling util.Arrays into the main class I have tried to impliment this:

}// end method main
	
	 public static void sort(char[] cds)	
		{
			var cds = new Cds[5];
			cds[0] = Name
			cds[1] = Name
			cds[2] = Name
			cds[3] = Name
			cds[4] = Name
		}	
		{
			return (Cds.sort(Name, String.CASE_INSENSITIVE_ORDER));
			trace("Array.sort():\n" + Cds);
		}
			
} // end class Payroll

I know it is not right, but for my first time I am just trying to get in the ballpark. Can someone tell me if I am even on the right track, or do I need to disregard this implimentation and try something else?
I just want to spit out a quick list of the cds in alphabetical order, by the name parameter.

I seem to be going in a big circle with this.
Latest version ends up like this:

public static void sort(char[] cds)
	{
 
	cds[0] = name; 
	cds[1] = name; 
	cds[2] = name; 
	cds[3] = name; 
	cds[4] = name; 
	}
	{
	return (Cds.sort(Name, String.CASE_INSENSITIVE_ORDER)); trace("Array.sort():\n" + Cds);
	} 

	
} // end class Payroll

and I am getting "cannot find symbol" errors for every instance of "name" I have. I would be grateful for any help. This is my first sort and I am not even sure I am using it right, much less the coding syntax issues.

I seem to be going in a big circle with this.
Latest version ends up like this:

public static void sort(char[] cds)
	{
 
	cds[0] = name; 
	cds[1] = name; 
	cds[2] = name; 
	cds[3] = name; 
	cds[4] = name; 
	}
	{
	return (Cds.sort(Name, String.CASE_INSENSITIVE_ORDER)); trace("Array.sort():\n" + Cds);
	} 

	
} // end class Payroll

and I am getting "cannot find symbol" errors for every instance of "name" I have. I would be grateful for any help. This is my first sort and I am not even sure I am using it right, much less the coding syntax issues.

Have you ever programmed in an object oriented language like Java before?

Problems with your code that I will point out then work on fixing:

1. name is not data in Java, "name" is a string, which is what you should be using.

2. You cannot have a "return" call with functions after it. Java just won't let you do that.

3. You can't change capitalization of the variables and have them work the same. Java isn't Visual Basic. :p

4. You cannot return data without declaring the method to be of that datatype (this is Java, not Javascript).

5. Printf is actually a new function designed to make print easier for newbie C programmers. It's much easier to just use +""+ (as you'll see in my example).


Fixes to make that code Java and not whatever you were trying to write it in:

import java.util.Scanner; //uses class Scanner

public class Inventory
{// begin class Inventory

	public static int maxlength = 0;
	 public static Compactdisk[] sort(Compactdisk[] cds)	
		{
				   
   //Bubble sort
      for (int i = 0; i < maxlength-1; i++){
         for (int j = i + 1; j < maxlength; j++){
            if (((Comparable)cds[i].getName()).compareTo(cds[j].getName()) > 0){
               Compactdisk temp = cds[i];
               cds[i] = cds[j];
               cds[j] = temp;
           		 }
        	  }
      		}
      		
      	return cds;
   		
		}
    public static String toString(Compactdisk[] cds)
    {
    	String toSend = "\n\n";
    	
    	for(int i = 0; i < maxlength; i ++)
    	 toSend = toSend + cds[i].getName() + "\n";
    	 return toSend;
    }
    
	public static void main(String[] args)	
	{//begin method main
	
	
	// create cd Array
	Compactdisk[] cds = new Compactdisk[5];
	
	cds[0] = new Compactdisk(); 	
	float totalValue = 0;
	
	Scanner input = new Scanner(System.in);  // create scanner
	
	
	
			// begin display method
			System.out.print("Enter up to 5 CD Names or STOP to Exit: ");
			String nameInput = input.nextLine(); //read cd name
			
			maxlength ++;			
			
		  	for(int i = 1; i < cds.length && !nameInput.equals("STOP"); i++)
			{// begin main While
			
				cds[i] = new Compactdisk();
				cds[i].setName(nameInput);

				System.out.print("Enter Price of this CD: "); // prompt for price
				cds[i].setPrice(input.nextFloat());	// price input from user.
				while (cds[i].getPrice()<= 0)
				{// begin while
				System.out.print("Price Must Be Greater Than Zero. Enter Price: ");
				cds[i].setPrice(input.nextFloat()); // cd price loop from user.
				} // End while
		
				System.out.print("Enter CD Item Number: "); // prompt for cd item number
				cds[i].setItemno(input.nextInt()); // cds item number input from user
		
				System.out.print("Enter Number of these CDs in Stock: "); // prompt for cd stock
				cds[i].setNstock(input.nextInt()); // cds in stock input from user
				
				        
				System.out.print("CD "+cds[i].getName()+", Item Number "+cds[i].getItemno()+","); // display name
				System.out.print("\nis worth: $"+ cds[i].getPrice()); // display individual price
				System.out.println("\nWe have "+ cds[i].getNstock() +" copies in stock, making our inventory for this cd worth: $"+ cds[i].getValue()); //inventory value
				
				if(cds[i].getValue() != -1)
					totalValue = totalValue + cds[i].getValue();
				
							
				System.out.println("Combined Inventory for all CDs is Worth: $"+ totalValue);
				
				System.out.print("Enter up to 5 CD Names or STOP to Exit: ");
				input=new Scanner(System.in); // internal loop prompt
				nameInput = input.nextLine(); //name input from user
				
				maxlength ++;
																
			} // End main While
			
		  //System.out.println(toString(cds));
		 System.out.println(toString(sort(cds)));
		System.out.print("Ending Program.");
	

	}// end method main
} // end class Payroll

This is using a simple bubblesort, which you will want to replace with your own sorting algorithm. You will also want to replace the toString method with a better formatted method of your own. This code isn't perfect, it really only demonstrates how to use Java function calls etc. The code does *work* however and performs the function that you want it to.

Example output:

Enter up to 5 CD Names or STOP to Exit: Hi Baby
Enter Price of this CD: 1
Enter CD Item Number: 2
Enter Number of these CDs in Stock: 3
CD Hi Baby, Item Number 2,
is worth: $1.0
We have 3 copies in stock, making our inventory for this cd worth: $3.0
Combined Inventory for all CDs is Worth: $3.0
Enter up to 5 CD Names or STOP to Exit: Crack and Java
Enter Price of this CD: 5
Enter CD Item Number: 6
Enter Number of these CDs in Stock: 2
CD Crack and Java, Item Number 6,
is worth: $5.0
We have 2 copies in stock, making our inventory for this cd worth: $10.0
Combined Inventory for all CDs is Worth: $13.0
Enter up to 5 CD Names or STOP to Exit: Hello World!
Enter Price of this CD: 5
Enter CD Item Number: 7
Enter Number of these CDs in Stock: 2
CD Hello World!, Item Number 7,
is worth: $5.0
We have 2 copies in stock, making our inventory for this cd worth: $10.0
Combined Inventory for all CDs is Worth: $23.0
Enter up to 5 CD Names or STOP to Exit: STIP
Enter Price of this CD: 1
Enter CD Item Number: 3
Enter Number of these CDs in Stock: 5
CD STIP, Item Number 3,
is worth: $1.0
We have 5 copies in stock, making our inventory for this cd worth: $5.0
Combined Inventory for all CDs is Worth: $28.0
Enter up to 5 CD Names or STOP to Exit: STOP



Crack and Java
Hello World!
Hi Baby
STIP

Ending Program.Press any key to continue...

I have never programmed in Java before. I have not programmed in anything since the late 80s when I used COBOL for awhile.
I appreciate your help. I will try and take what you have shown me here and apply it to my program.
Once I get everything completed I will post the final product, or more questions ... care to guess which one will come first? :o)

I have never programmed in Java before. I have not programmed in anything since the late 80s when I used COBOL for awhile.
I appreciate your help. I will try and take what you have shown me here and apply it to my program.
Once I get everything completed I will post the final product, or more questions ... care to guess which one will come first? :o)

Actually, I did you a bit of a favor and I rewrote your sort method using the Java default mergesort using the abstract class Arrays.


Changes to Inventory.java

//uses class Scanner
import java.util.*;

public class Inventory
{// begin class Inventory

	public static int maxlength = 0;
	 public static Compactdisk[] sort(Compactdisk[] cds)	
		{
				   
          Arrays.sort(cds, 0, maxlength);
      		
      	return cds;
   		
		}
    public static String toString(Compactdisk[] cds)
    {
    	String toSend = "\n\n";
    	
    	for(int i = 0; i < maxlength; i ++)
    	 toSend = toSend + cds[i].getName() + "\n";
    	 return toSend;
    }
    
	public static void main(String[] args)	
	{//begin method main
	
	
	// create cd Array
	Compactdisk[] cds = new Compactdisk[5];
	
	cds[0] = new Compactdisk(); 	
	float totalValue = 0;
	
	Scanner input = new Scanner(System.in);  // create scanner
	
	
	
			// begin display method
			System.out.print("Enter up to 5 CD Names or STOP to Exit: ");
			String nameInput = input.nextLine(); //read cd name
			
			maxlength ++;			
			
		  	for(int i = 1; i < cds.length && !nameInput.equals("STOP"); i++)
			{// begin main While
			
				cds[i] = new Compactdisk();
				cds[i].setName(nameInput);

				System.out.print("Enter Price of this CD: "); // prompt for price
				cds[i].setPrice(input.nextFloat());	// price input from user.
				while (cds[i].getPrice()<= 0)
				{// begin while
				System.out.print("Price Must Be Greater Than Zero. Enter Price: ");
				cds[i].setPrice(input.nextFloat()); // cd price loop from user.
				} // End while
		
				System.out.print("Enter CD Item Number: "); // prompt for cd item number
				cds[i].setItemno(input.nextInt()); // cds item number input from user
		
				System.out.print("Enter Number of these CDs in Stock: "); // prompt for cd stock
				cds[i].setNstock(input.nextInt()); // cds in stock input from user
				
				        
				System.out.print("CD "+cds[i].getName()+", Item Number "+cds[i].getItemno()+","); // display name
				System.out.print("\nis worth: $"+ cds[i].getPrice()); // display individual price
				System.out.println("\nWe have "+ cds[i].getNstock() +" copies in stock, making our inventory for this cd worth: $"+ cds[i].getValue()); //inventory value
				
				if(cds[i].getValue() != -1)
					totalValue = totalValue + cds[i].getValue();
				
							
				System.out.println("Combined Inventory for all CDs is Worth: $"+ totalValue);
				
				System.out.print("Enter up to 5 CD Names or STOP to Exit: ");
				input=new Scanner(System.in); // internal loop prompt
				nameInput = input.nextLine(); //name input from user
				
				maxlength ++;
																
			} // End main While
			
		  //System.out.println(toString(cds));
		 System.out.println(toString(sort(cds)));
		System.out.print("Ending Program.");
	

	}// end method main
} // end class Payroll

Changes to Compactdisk.java

import java.lang.Comparable;
public class Compactdisk implements Comparable
{// begin class

	//InventoryCD class has 5 fields
	String name; //  Name of cd
	float price; // price of cd
	int itemno; // item number of cd
	int nstock; // how many units in stock	
	int i; // cd counter for array
	float value; // value for single cd inventory

	
	//Compact disk class constructor
	public Compactdisk()
	
		// 4 fields need to be set up
		{ 
		name = "";
		price = 0;
		itemno = 0;
		nstock = 0;
		i = 0;
		value = 0;
			}
		
		// set values
	   public void setName(String diskName)
	   {
	   name = diskName;
	   }
		public void setPrice(float cdPrice)
	   {
	   price = cdPrice;
	   }
		public void setItemno(int cdItemno)
	   {
	   itemno = cdItemno;
	   }
		 public void setNstock(int cdStock)
	   {
	   nstock = cdStock;
	   }
		public void setValue(float cdValue)
		{
		value = cdValue;
		}
		public void seti(int Count)
		{
		i = Count;
		}
	
		
	   // return values
		public String getName()
		{	
		return (name);
		}
		public float getPrice()
		{	
		return (price);
		}
		public int getItemno()
		{	
		return (itemno);
		}
		public int getNstock()
		{	
		return (nstock);
		}
	
					
		// returns indivudual inventory value for a disk
	   public float getValue()
	   {
	   return(price * nstock);
	   }
		
			
	   public int compareTo(Object in)
	   {
	   	return ((Comparable)name.toLowerCase()).compareTo((Comparable)((Compactdisk)in).getName().toLowerCase());
	   }
		
			
}// end class

Output:

Enter up to 5 CD Names or STOP to Exit: XYZ
Enter Price of this CD: 1
Enter CD Item Number: 2
Enter Number of these CDs in Stock: 3
CD XYZ, Item Number 2,
is worth: $1.0
We have 3 copies in stock, making our inventory for this cd worth: $3.0
Combined Inventory for all CDs is Worth: $3.0
Enter up to 5 CD Names or STOP to Exit: abc
Enter Price of this CD: 5
Enter CD Item Number: 3
Enter Number of these CDs in Stock: 2
CD abc, Item Number 3,
is worth: $5.0
We have 2 copies in stock, making our inventory for this cd worth: $10.0
Combined Inventory for all CDs is Worth: $13.0
Enter up to 5 CD Names or STOP to Exit: mmmmmm
Enter Price of this CD: 4
Enter CD Item Number: 2
Enter Number of these CDs in Stock: 1
CD mmmmmm, Item Number 2,
is worth: $4.0
We have 1 copies in stock, making our inventory for this cd worth: $4.0
Combined Inventory for all CDs is Worth: $17.0
Enter up to 5 CD Names or STOP to Exit: STOP



abc
mmmmmm
XYZ

Ending Program.Press any key to continue...
commented: Helpful code. He isn't quite to the point of understanding the use of Comparable interfaces, but at least he can see the correct way to do it. +2

If you stop back in to read that, that second post is the one you want to go with as most the work is done for you.


Cheers,
-TheGathering

That was way more than I expected to see. It did answer all of my questions though. I am going to try some different things with it and let you know how it comes out.
I was unsure of the maxlenght, and how it worked, and could not find a good coding example for arrays.sort for me to use. Or so I thought. The INT was throwing me off as the object I am trying to sort on is a string. But I think I have it now. The tosend is still way beyond me, I am doing some reading on that this afternoon.
thanks again guys. you make all the frustration bearable in the end.

If you stop back in to read that, that second post is the one you want to go with as most the work is done for you.


Cheers,
-TheGathering

I kept that sort in there, it was simple and I understand it (for the most part.)
I have completed work on this issue, but wanted to pick your brain on a few blocks of code that I do not think I fully understand.
Can you give me a play by play (in laymans terms) exactly what a few of these blocks are doing?
For instance:

public int compareTo(Object in)
	   {
	   	return ((Comparable)name.toLowerCase()).compareTo((Comparable)((Compactdisk)in).getName().toLowerCase());
	   }

I do not understand exactly what this is doing, other than comparing the names I have entered and returning them in order. I do not understand the mechanics behind it. And

public static String toString(Compactdisk[] cds)
    {
    	String toSend = "\n\n";
    	
    	for(int i = 0; i < maxlength; i ++)
    	 toSend = toSend + cds[i].getName() + "\n";
    	 return toSend;
    }

I think this keeps track of the number of elements entered so that the loop knows when to end, but I am not sure exactly how it does it. Maxlenth is much like count, but I do not get the "toSend" part.

I know you are not my teacher or anything, but this code intrigues me and I would like to learn all I can. I have never seen these used before, and would not be able to effectively use them again without further explaination.

Thanks for any detail you might be willing to offer.

I kept that sort in there, it was simple and I understand it (for the most part.)
I have completed work on this issue, but wanted to pick your brain on a few blocks of code that I do not think I fully understand.
Can you give me a play by play (in laymans terms) exactly what a few of these blocks are doing?
For instance:

public int compareTo(Object in)
	   {
	   	return ((Comparable)name.toLowerCase()).compareTo((Comparable)((Compactdisk)in).getName().toLowerCase());
	   }

I do not understand exactly what this is doing, other than comparing the names I have entered and returning them in order. I do not understand the mechanics behind it.

For that version of Arrays.sort, Java requires that the Compactdisk class have some way of comparing against another Compactdisk class (so that order can be determined). The way this is done is by making Compactdisk implement the Comparable abstract class methods. Essentially this means that Java recognizes Compactdisk as of the Comparable object type because the Compactdisk performs the same functions as the Comparable object as defined by the abstract class (think of it like a blueprint). compareTo is the only method that needs to be implemented for Compactdisk to implement the Comparable class.

That one line method does a few things in this order:
1.) It gets the current name value from itself (as a String)

2.) Casts the String it to a Comparable object so it can call compareTo from the Comparable object layer.

3.) Calls compareTo on the Comparable object layer against the object in the parameter:

4.) Converts the Object in parameter into a Compactdisk object (since that is what we are using the compareTo for in this instance).

5.) Gets the name from the parameter object that has been cast to a Compactdisk object.

6.) Makes the name lower case (so that it is not case sensitive).

7.) Casts the lower case name String to a Comparable object

8.) Runs the compareTo on the Comparable object layer against the string mentioned in 7.

9.) Returns the number value that was returned by step 8 (less than 0 of the first is less than the second, 0 if they are equal, and greater than 0 if the first is greater than the second).

And

public static String toString(Compactdisk[] cds)
    {
    	String toSend = "\n\n";
    	
    	for(int i = 0; i < maxlength; i ++)
    	 toSend = toSend + cds[i].getName() + "\n";
    	 return toSend;
    }

I think this keeps track of the number of elements entered so that the loop knows when to end, but I am not sure exactly how it does it. Maxlenth is much like count, but I do not get the "toSend" part.

I know you are not my teacher or anything, but this code intrigues me and I would like to learn all I can. I have never seen these used before, and would not be able to effectively use them again without further explaination.

Thanks for any detail you might be willing to offer.

toSend is the String object name that I prefer to use in my toString methods. A toString method is a method that overwrites the default toString in the Object class (which all objects extend). If you were to simply print the Inventory object with no other calls such that:

Inventory inv = new Inventory();
(add items to Inventory)
...
System.out.println(inv);

the toString in Inventory would automatically be called by println without it having to be specified. Maxlength is similar to counter in that it holds how many elements are in your array, but I prefer to use maxlength over count because I used to use count instead of 'i' for my loops :p.

What that method does specifically is iterates through the populated objects held in cds and adds their name value to the String toSend such that:

first element, toSend looks like:
1
second element, toSend looks like:
1
2
third element, toSend looks like:
1
2
3

etc...

It then returns the toSend string to the calling method (this time System.out.println(); found in main() to be printed),

I appreciate that. It helps me so much to have that kind of explaination.
I can see the code in my application, run through it line by line, and see what triggers what now.
A lot of the time I am just using code because it is what I have learned, but do not know the specifics of what it does. It will help me in the long run to get this kind of detailed instruction, and my instructor in class just does not have this kind of individual time to set aside for each student.
Again, thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.