Beginner to Java: Constructors and Sorts

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Misaio
    New Member
    • Mar 2010
    • 16

    Beginner to Java: Constructors and Sorts

    I am a beginner programmer and am having trouble with constructors and sorts. What's worse is that I am not used to programming in two different classes. It's making my head spin looking back and forth trying to trace the different names.

    The idea behind the project is that I'm going to have two sets of arrays. One with item names and the other with the corresponding prices of said items. The user will be asked how they wish to see the information sorted. (Either alphabetically by the names or numerically by price.) Then I have them sorted (depending on the user input) and display them.

    Now, I know I'll need two different classes for this and a constructor. Do I define the arrays in the constructor with a get/set in one class and sort in the driver class? Any examples, links, or advice would be GREATLY appreciated. I will give kudos for even the slightest nudge in the right direction.

    ~Missy
  • pbrockway2
    Recognized Expert New Member
    • Nov 2007
    • 151

    #2
    Is there some reason why you want two arrays? It would be a lot easier if you had a class representing the name and price of an article. And a single array of articles which you sorted ad displayed.

    Comment

    • Misaio
      New Member
      • Mar 2010
      • 16

      #3
      I think I'm supposed to use two arrays for the project. Let me grab some of the criteria for you. I have started to put some of the code together, but I'm confused as to where I declare the array objects. Also, I was told that bubble sorting would be a good way to try this, but I've never used it. Can anyone give me information on that?

      This project will require 2 classes. The first will be the data definition class and the second class will contain the main.
      First class name Item:

      Data Fields are 2 only and remember these data fields should be private.

      String itemName;
      double itemPrice;

      The public methods for this class will be the following:

      A constructor the takes a String and a double as the input arguments to initialize the data fields.

      getItemName
      setItemName
      getItemPrice
      setItemPrice

      Now on to the second class to be called CoffeeDriver which will contain the main method.

      Methods required for the Driver class:

      main - will create an array of Item Objects using the data above to set each item’s information. This information will NOT come from the user of the project. In addition, main should request from the user which order they wish to see the data items list, by price or by item name. Use a JOptionpane for this request. You might want to include a question to ask the user if they are finished with the program??

      sortName this method will sort the array of item objects by the item name. Remember when creating your sort that when you are comparing String values you cannot use ==. You will want to use the compareTo() String method. See note below. You must also keep in mind that you will compare on the String of the item name only, but when you need to swap for the sort, you will be swapping a complete object which includes the name and price, not just the itemNames. This method will display the array of objects in item name order. The display will include both the itemName and the itemPrice.

      sortPrice: this method will sort the array of item objects by price. Again remember, when you need to swap the prices, you are swapping the entire object and not just the prices. Again this method will display the array of objects in price order. The display will include both the itemName and the itemPrice.

      Comment

      • pbrockway2
        Recognized Expert New Member
        • Nov 2007
        • 151

        #4
        This project will require 2 classes. The first will be the data definition class and the second class will contain the main.
        This makes it sound even more like I described. The "data definition" is a class (what I was calling an article) that includes both the name and the price.

        As the description of the driver class says, it: "will create an array of Item Objects using the data above". There is only a single array involved.

        I suggest you start with the data definition class as this is the most straight forward: a class with a couple of instance fields (each with get/set mutator methods) and a constructor. Post code if you get stuck.

        Then you can start writing the driver class whose three (static?) methods do exactly what was described in the assignment. The ugly details of implementing the sort can be found on Wikipedia or your textbook.

        Again to repeat the point made in the assignment description: the main() method of the driver class begins by creating a single array of instances of the other (data) class.

        Comment

        • Misaio
          New Member
          • Mar 2010
          • 16

          #5
          Alright, I was actually giving this a shot to see what I could put together. I know, I'm missing a lot of the key elements, but so far, how does it look?

          Code:
          import java.util.Arrays
          import javax.swing.JOptionPane;
          public class CoffeeDriver
          {
          	public static void main (String[] args)
          	{
          		String userInput;
          		int x;
          		int selectSort;
          		String[] someItem = new String[5];
          		double[] somePrice = new double[5];
          		//Just incase, I always have this final int until I'm ready to complete the program.
          		final int PLACE_HOLDER = 6;
          		JOptionPane.showMessageDialog(null, "Welcome to The Coffee Shop!");
          		userInput = JOptionPane.showInputDialog(null, "Please indicate how you would like to sort the menu.  To sort by price, press 1.  To sort by name, press 2.  To exit the program, press 3.");
          		selectSort = Integer.parseInt(userInput);
          		if (selectSort < 1 || selectSort > 3);
          			JOptionPane.showMessageDialog(null, "Please enter a valid selection.");
          		//Not finished with this yet
          		if (selectSort == 1);
          			sortPrice();
          		//Still not complete here.
          		if (selectSort == 2);
          			sortName();		
          		//given option to end program
          		if (selectSort == 3);
          			JOptionPane.showMessageDialog(null, "Thank you for using Wings Coffee Shop.  Have a great day!");
          	}
          	public static double sortPrice();
          	{
          	//will have my double sorted for my Price Array here
          	}
          	public static String sortName();
          	{
          	//Will have my string sorted for my Name Array here
          	}
          }
          Code:
          public class item
          {
          	private String itemName;
          	private double itemPrice;
          	public String getName()
          	{
          		return itemName;
          	}
          	public double getPrice;
          	{
          		return itemPrice;
          	}
          	public item (String itemName, double itemPrice)
          	{
          		double[] ItemPrice = {0.0, 1.00, 2.00, 1.50, 1.25, 0.75};
          		String[] ItemName = {"Item", "Coffee", "Water", "Milk", "Bagel", "Donut"};
          	}
          	public void setItemName(String someItem)
          	{
          		itemName = someItem;
          	}
          	public void setItemPrice(double somePrice)
          	{
          		itemPrice = somePrice;
          	}
          }

          Comment

          • Misaio
            New Member
            • Mar 2010
            • 16

            #6
            Now I'm a little less confused on what I need. Thank you! Now...how do I go about putting the item with the price in one array? And was I right to attempt to define the item objects in the constructor? I know, I sound like a really dim girl, but I'm doing my best to fully grasp the terms and how these concepts are applied, I promise. I really want to learn the basics of programming so I can move on to better things.

            Comment

            • pbrockway2
              Recognized Expert New Member
              • Nov 2007
              • 151

              #7
              A constructor the takes a String and a double as the input arguments to initialize the data fields.
              So the item constructor should look like this:

              Code:
              public item (String itemName, double itemPrice)
              {
                  this.itemPrice = itemPrice;
                  this.itemName = itenName;
              }
              (and the class should be renamed to start with a capital letter: Item)

              Other than that the Item class looks good. It acts as a self contained unit that other classes (like the driver) can use.

              Notice that the assignment was very clear that the driver's main() method creates the Item instances. So there is no reason for the String and double arrays in the Item constructor.

              -----

              sortName this method will sort the array of item objects by the item name.
              There is nothing here that suggests that sortName() should return a String. (what String should it return?) There is some ambiguity in the assignment here: should the method create a whole new, sorted, array? or should it take an array argument and sort it "in place"? I'll assume the latter approach in which case the method - together with its necessary documentation comment - looks like:

              Code:
                      /** Sorts a given array of Items in place and displays it. */
                  private static void sortName(Item[] arr)
                  {
                      // TODO - sort the array using getName()
              
                      // TODO - use a for loop to print the array contents
                  }
              (private at this stage because there's no reason for it to not be private. Note that there seems no good reason for this method to both sort and display. There should be separate methods for these very different tasks. But your assignment says the method should do both, so that's what you've got to do.)

              The other one is similar.

              main - (A) will create an array of Item Objects using the data above to set each item’s information. This information will NOT come from the user of the project. (B) In addition, main should request from the user which order they wish to see the data items list, by price or by item name. Use a JOptionpane for this request. (C) You might want to include a question to ask the user if they are finished with the program?
              Your main() method doesn't resemble the assignment's description at all! I've added letters to each point in that description. Just do what it says, in the order it says:

              Code:
              public static void main(String[] args)
              {
                      // A
                  Item arr = new Item[/*however many you want*/];
                  arr[0] = new Item(/*first name and price*/);
                  arr[1] = new Item(/*second name and price*/);
                  // etc
              
                      // B
                  int selectSort;
                  // TODO: Use a JOptionPane to give selectSort the appropriate value
              
                  if(selectSort == 1)
                  {
                      sortPrice(arr);
                  }
                  else if(selectSort == 2)
                  {
                      sortName(arr);
                  }
              
                      // C
                  // TODO - ???
              }
              (Note the use of braces near the end. You're code didn't use them and, as a result, didn't mean what you thought.)

              It might be a good idea to delay working on point (C) until the rest is working OK. At this point you want to have code that both compiles and prints something (in the sort methods) you can check.

              Comment

              • pbrockway2
                Recognized Expert New Member
                • Nov 2007
                • 151

                #8
                Our posts crossed - but I think I made the point about using a single array a bit more precise. (Say if not.)

                Comment

                • Misaio
                  New Member
                  • Mar 2010
                  • 16

                  #9
                  pb:

                  Thank you, thank you, thank you! I think I see just what you're talking about now. And thank you for just explaining what I'm missing rather than showing me code. I don't want to get in trouble for that. I really want to write the code myself, not copy and paste. Let me try to revamp my code and I'll keep you updated. Hopefully, I'll be able to finish this quickly! So don't go far. Heh.

                  ~Missy

                  PS: I think I understand what you were saying about a single array. Your points on that were BRILLIANT. But I'm not 100% sure as to how it would be able to sort the names alphabetically in one point and the numbers from lowest to highest in another sort if they are together. Could you explain this for me? I know I've asked for a lot from you. But I wanna grow up to code just like you.

                  Comment

                  • Misaio
                    New Member
                    • Mar 2010
                    • 16

                    #10
                    Oh! Another question...you mentioned that:
                    Code:
                    9.	        // B
                    10.	    int selectSort;
                    11.	    // TODO: Use a JOptionPane to give selectSort the appropriate value
                    But I was under the impression that since I was getting it as user input that it was a String by default and that I should parse it to an int. That's why userInput and selectSort were so different.

                    Code:
                    	userInput = JOptionPane.showInputDialog(null, "Please indicate how you would like to sort the menu.  To sort by price, press 1.  To sort by name, press 2.  To exit the program, press 3.");
                    		selectSort = Integer.parseInt(userInput);

                    Comment

                    • pbrockway2
                      Recognized Expert New Member
                      • Nov 2007
                      • 151

                      #11
                      Elsewhere on teh internet, Faye Rett was directed towards Wikipedia's list of sorting algorithms. The simple bubble sort is probably easiest to understand - the article gives an explanation and an example before moving on to the code.

                      The first implementation given in the wikipedia article should be fairly easy to implement in Java. The thing to understand is that when the code says:

                      Code:
                      if A[i] > A[i+1] then
                      you will have something like

                      Code:
                      if(arr[i].getPrice() > arr[i+1].getPrice())
                      {
                      or

                      Code:
                      if(arr[i].getName().compareTo(arr[i+1].getName) > 0)
                      {
                      -----

                      Also where the pseudocode says "swap( A[i], A[i+1] )" you will need to use a temporary variable:

                      Code:
                      Item temp = arr[i];
                      arr[i] = arr[i+1];
                      arr[i+1] = temp;
                      -----

                      The ball is basically in your court: to take that bubble sort pseudocode and come up with your sortName() and sortPrice() methods. Good luck! The worst that can happen is that you'll end up with some crazy output, but in that case just post the code you are using and the (unwanted) results you get when you run it.

                      Comment

                      • Misaio
                        New Member
                        • Mar 2010
                        • 16

                        #12
                        Thanks mate! This should keep me busy for the remainder of the night. It's nice to see some experts around here that are so willing to help. I'll keep you posted with the results!

                        Comment

                        • pbrockway2
                          Recognized Expert New Member
                          • Nov 2007
                          • 151

                          #13
                          But I was under the impression that since I was getting it as user input that it was a String by default and that I should parse it to an int.
                          Yes, that's quite correct. There was nothing wrong with how you were getting the int value for selectSort: display a dialog, get a String result, convert it to an int. There are other ways of proceeding, I guess, but yours sounds OK.

                          Comment

                          • pbrockway2
                            Recognized Expert New Member
                            • Nov 2007
                            • 151

                            #14
                            I'll keep you posted with the results!
                            I'll be offline for a while, but I'll be sure to check back on progress.

                            Comment

                            • Misaio
                              New Member
                              • Mar 2010
                              • 16

                              #15
                              Alright, so now I have what I believe is a nice way to hold both pieces of the corresponding data under one [x].

                              Code:
                              		Item arr[] = new Item[5];
                              		arr[0] = new Item("Coffee", 1.00);
                              		arr[1] = new Item("Water", 2.00);
                              		arr[2] = new Item("Milk", 1.50);
                              		arr[3] = new Item("Bagel", 1.25);
                              		arr[4] = new Item("Donut", 0.75);
                              Now my problem is, I don't know how to pass the entire array of objects to my method. I keep getting errors when I try. Here is how I attempt to pass it.

                              Code:
                              	sortPrice(arr);
                              	public static void sortPrice(Item arr[]);
                              Error: CoffeeDriver.ja va:36: missing method body, or declare abstract
                              public static void sortPrice(Item arr[]);
                              ^

                              Any ideas?

                              Comment

                              Working...