Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 10 of 10

Thread: how to sort array by object string member value?

  1. #1
    Junior Member
    Join Date
    Feb 2012
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Exclamation how to sort array by object string member value?

    I am trying to sort the 'stock' array (which is made up of Product objects) by the item name of each Product object. Before I start hacking at my code (which works well right now), I want to know if anyone can explain how I can sort this array by the String itemname of each Product object before output. Any help is much appreciated.

     
    // Product.java
    // Product class for Inventory Program
    // Adam Gleason IT/215 2012
     
    package inventory;                                                              //Declare package inventory
     
    public class Product {                                                          //Declare class Product
     
        public int itemnumber;                                                      //Declare integer itemnumber
        public String itemname;                                                     //Declare string itemname
        public int units;                                                           //Declare integer units
        public double price;                                                        //Declare double price
     
        public Product ( int newitemnumber, String newitemname, int newunits, double newprice)  //constructor for class Product
        {
            itemnumber = newitemnumber;                                             //Initialize integer newitemnumber
            itemname = newitemname;                                                 //Initialize string newitemname
            units = newunits;                                                       //Initialize integer newunits
            price = newprice;                                                       //Initialize integer newprice
        }
        public int getItemNumber()                                                  //Declare method getItemNumber
        {
            return itemnumber;                                                      //Return itemnumber
        }
        public String getItemName()                                                 //Declare method getItemName
        {
            return itemname;                                                        //Return itemname
        }
        public int getUnits()                                                       //Declare method getUnits
        {
            return units;                                                           //Return units
        }
        public double getPrice()                                                    //Declare method getPrice
        {
            return price;                                                           //Return price
        }
        public double calculateValue()                                              //Declare method calculateValue
        {
            return units * price;                                                   //return value calculation
        }
    }                                                                               //End class Product
     
     
    // Inventory.java
    // Exercise with input exception handling
    // Adam Gleason IT/215 2012
     
    package inventory;                                                              //Declare package inventory
     
    import java.util.InputMismatchException;                                        //Import definition for InputMismatchException
    import java.util.Scanner;                                                       //Import definition for Scanner
    import java.util.Arrays;
     
    public class Inventory {                                                        //Declare class Inventory
     
     
        public static void main(String[] args) {                                    //Declare method main
     
            String stop;                                                            //Declare sentinal string stop
            int result;                                                             //declare sentinal int result
     
            Scanner input = new Scanner (System.in);                                //Declare new scanner object
     
            int itemnumber;                                                         //Delcare int itemnumber
            String itemname;                                                        //Delcare string itemname
            int units;                                                              //Delcare integer units
            double price;                                                           //Declare double price
            Product[] stock;  //new
            stock = new Product[100];
            int counter = 0;  //new
     
     
            stop = "stop";                                                          //Initialize sentinal string stop
            result = 1;                                                             //Initialize sentinal integer result
     
            System.out.print("Welcome to the Inventory Program");                   //Welcome message
     
            while (result != 0)                                                     //Repetition statement for multiple product input
                {
                    System.out.print( "\n\nEnter the item name (enter 'stop' to quit):" );  //Prompt for string itemname
                    itemname = input.nextLine();                                    //Input string itemname
                    result = itemname.compareTo(stop);                              //Compare sentinal string
     
                    if (result !=0)                                                 //Test sential integer
                    {
                        boolean itemnumberloop = true;                              //Initialize intemnumberloop repetion statement
                        itemnumber = 0;                                             //Initialize integer itemnumber
     
                        while (itemnumberloop)                                      //Begin intemnumberloop repetition statement
                        {
                            try                                                     //Try statement for valid input
                            {   
                                int test = 0;                                       //Initialize test variable
                                System.out.print("Enter the Item Number: ");        //Prompt for integer itemnumber
                                itemnumber = input.nextInt();                       //Input integer itemnumber
                                test = itemnumber / 1;                              //Test for valid input type
     
                                while (itemnumber < 0)                              //test for valid integer input
                                {
                                System.out.println("That is an invalid item number, please try again"); //Display invalid integer input message
                                System.out.print("Enter the Item Number: ");        //Prompt for integer itemnumber
                                itemnumber = input.nextInt();                       //Input integer itemnumber
                                }
     
                                itemnumberloop = false;                             //End itemnumberloop repetition statement after valid input
                                test = 0;                                           //nullify value of test statement
                            }
     
                            catch (InputMismatchException inputMismatchException)   //Exception statement for invalid input type
                            {
                                System.err.printf("\nError: %s\n", inputMismatchException); //Display error message
                                input.nextLine();                                   //nullify invalid input
                                System.out.println("You must input an integer, please try again\n");    //Display invalid input type message
                            }
                        }
     
                        boolean unitsloop = true;                                   //Initialize unitsloop repetition statement
                        units = 0;                                                  //initialize integer units
     
                        while (unitsloop)                                           //Begin unitsloop repetition statement
                        {
                            try                                                     //Try statement for valid input
                            {
                                int test = 0;                                       //Initialize test variable
                                System.out.print("Enter the number of units: ");    //Prompt for integer units
                                units = input.nextInt();                            //Input integer units
                                test = units / 1;                                   //Test for valid input type
     
                                while (units < 0)                                   //Repition statement for valid integer input
                                {
                                    System.out.println("That is an invalid number of units, please try again");  //Display invalid integer input message
                                    System.out.print("Enter the number of units: ");//Prompt for integer units
                                    units = input.nextInt();                        //Input integer units
                                }
     
                                unitsloop = false;                                  //End unitsloop repetition statement after valid input
                                test = 0;                                           //nullify test variable
                            }
     
                            catch (InputMismatchException inputMismatchException)   //Exception statement for invalid input type
                            {
                                System.err.printf("\nError: %s\n", inputMismatchException); //Display error message
                                input.nextLine();                                   //nullify invalid input
                                System.out.println("You must input an integer, please try again\n");    //Display invalid input message
                            }
                        }
     
                        boolean priceloop = true;                                   //Initialize pricelooop repetition statement
                        price = 0;                                                  //Initialize double price
     
                        while (priceloop)                                           //Begin priceloop repettion statement
                        {
                            try                                                     //Try statement for valid input
                            {
                                double test = 0;                                    //Initialize test variable
                                System.out.print("Enter the price for each unit: ");//Prompt for double price
                                price = input.nextDouble();                         //Input double price
                                test = price / 1;                                   //Test for valid input type
     
                                while (price < 0)                                   //Repetition statement for valid double input
                                {
                                    System.out.println("That is an invalid price, please try again"); //Display invalid double input message
                                    System.out.print("Enter the price for each unit: "); //Prompt for double price
                                    price = input.nextDouble();                     //Input double price
                                }
     
                                priceloop = false;                                  //End priceloop repetition statement after valid input
                                test = 0;                                           //nullify test variable
                            }
     
                            catch (InputMismatchException inputMismatchException)   //Exception statement for invalid input type
                            {
                                System.err.printf("\nError: %s\n", inputMismatchException); //Display error message
                                input.nextLine();                                   //nullify invalid input
                                System.out.println("You must input a number, please try again\n"); //Display invalid input type message
                            }
                        }
     
                       stock[ counter ] = new Product (itemnumber, itemname, units, price);
                       counter++;  //new
     
                                                                                    //Display output using Product class methods
     
                        itemname = input.nextLine();                                //nullify string itemname for sentinal comparison
                    }
     
                    else
                    {
                        for (int count = 0; count < counter; count++)
                            System.out.printf("\n\nItem Number: %d\nItem Name: %s\nUnits in stock: %d\nPrice per unit: $%.2f\nTotal value of inventory: $%.2f", stock[count].getItemNumber(), stock[count].getItemName(), stock[count].getUnits(), stock[count].getPrice(), stock[count].calculateValue());
     
                        double total = 0;
                        for (int i = 0; i < counter; i++)
                            total += stock[i].calculateValue();
     
                        System.out.printf("\n\nTotal value of all inventory items: $%.2f", total);
                        System.out.println("\n\nThank you for using the Inventory Program");  //Display exit message after sentinal input
                    }                               
     
            }                                                                       //End repetition statement for multiple product input
        }                                                                           //End method main
    }                                                                               //End class Inventory


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: how to sort array by object string member value?

    Write a sort method that Compares the itemName members when making the decision on how to order the elements in the array.
    Last edited by Norm; March 16th, 2012 at 04:00 PM.

  3. #3
    Junior Member
    Join Date
    Feb 2012
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: how to sort array by object string member value?

    Ok, so I added this for loop at the beginning of the final else statement to display the output. It should compare the strings from each entry in the array. However, I am getting an error message that says Exception in thread "main" java.lang.NullPointerException whenever it gets to this line:

    if(stock[b].getItemName().compareToIgnoreCase(stock[a].getItemName()) < 0)

     else
                    {
                        for(int a = 0; a < stock.length; a++)
                        {
                            for(int b = a + 1; b < stock.length; b++)
                            {
                                if(stock[b].getItemName().compareToIgnoreCase(stock[a].getItemName()) < 0)
                                {
                                    Product[] temp = { stock[a] };
                                    stock[a] = stock[b];
                                    stock[b] = temp[0];
                                }
                            }
                        }
     
                        for (int count = 0; count < counter; count++)
                            System.out.printf("\n\nItem Number: %d\nItem Name: %s\nUnits in stock: %d\nPrice per unit: $%.2f\nTotal value of inventory: $%.2f", stock[count].getItemNumber(), stock[count].getItemName(), stock[count].getUnits(), stock[count].getPrice(), stock[count].calculateValue());
     
                        double total = 0;
                        for (int i = 0; i < counter; i++)
                            total += stock[i].calculateValue();
     
                        System.out.printf("\n\nTotal value of all inventory items: $%.2f", total);
                        System.out.println("\n\nThank you for using the Inventory Program");  //Display exit message after sentinal input
                    }                               
     
            }                                                                       //End repetition statement for multiple product input
        }                                                                           //End method main
        public static void SortByName( Product[] array )
        {
            for(int a = 0; a < array.length; a++)
            {
                for(int b = a + 1; b < array.length; b++)
                {
                    if(array[b].getItemName().compareToIgnoreCase(array[a].getItemName()) < 0)
                    {
                        Product[] temp = { array[a] };
                        array[a] = array[b];
                        array[b] = temp[0];
                    }
                }
            }
     
        }
    }                                                                               //End class Inventory

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: how to sort array by object string member value?

    Which variable in that statement has a null value?
    Print out the values of all the variables in that line to see which variable has a null value. Then try to find out why it does not have a valid value.

    You don't need to use any array when you save an element. Use a variable:
    Product temp = stock[a] ;
    and
    array[b] = temp;

  5. #5
    Junior Member
    Join Date
    Feb 2012
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: how to sort array by object string member value?

    ok, I changed it up a bit trying to get this right. I am still getting the null value error message though. Please help me understand how I should go about printing those values in the correct spot to identify which one returns a null value.

    String compare;
                        Product temp = new Product ( 1, "a", 1, 1);
                        for(int a = 0; a < stock.length; a++)
                        {
                            for(int b = a + 1; b < stock.length; b++)
                            {
                                compare = stock[a].itemname;
                                if(stock[b].itemname.compareToIgnoreCase(compare) < 0)
                                {
                                    temp = stock[a];
                                    stock[a] = stock[b];
                                    stock[b] = temp;
                                }
                            }
                        }

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: how to sort array by object string member value?

    ill getting the null value error message
    You need to find the variable with the null value.
    Add a println just in front of the line where the NPE occurs. Print the values of all the variables.

  7. #7
    Junior Member
    Join Date
    Feb 2012
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: how to sort array by object string member value?

    I have printed the values stored in stock[a], stock[b], temp, and compare just to make sure that everything was returning a value, not only did they all return a value, but the correct value as well. The null pointer exception error keeps pointing to this line

    if(stock[b].getItemName().compareToIgnoreCase(compare) < 0)

    *also has been written as if(stock[b].itemname.compareToIgnoreCase(compare) < 0)

    I printed the values before and after this line and everything is returning the correct string value. Yet the null pointer exception error points to this line. Could it have something to do with the comparison to 0? I am really hitting a wall on this one. Please help.

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: how to sort array by object string member value?

    Did you print this: stock[b].getItemName()
    it returns a reference that is used to access the compare...To() method

  9. #9
    Junior Member
    Join Date
    Feb 2012
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: how to sort array by object string member value?

    yes, i printed...

    stock[a].getItemName()
    stock[a].itemname
    stock[b].getItemName()
    stock[b.itemname
    temp.getItemName()
    temp.itemname
    compare

  10. #10
    Junior Member
    Join Date
    Feb 2012
    Posts
    9
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: how to sort array by object string member value?

    I have figured it out....

    apparently, the problem was with the looping statement that used variable b and what stock[b] was pointing to. I changed the statement to say this...

    for(int b = a + 1; b < counter; b++)

    using the counter that i used to when adding items to the stock array rather than using stock.length ( could probably have used stock.length-1 as well).

    Thank you for all of your help, it has helped tremendously. The program works beautifully now.

Similar Threads

  1. [SOLVED] Instance data member vs Local variables (primitive/object reference)
    By chronoz13 in forum Java Theory & Questions
    Replies: 1
    Last Post: September 23rd, 2011, 12:42 AM
  2. Bubble Sort Int Array Problem
    By thisbeme in forum Collections and Generics
    Replies: 1
    Last Post: September 11th, 2011, 09:24 AM
  3. Reading from ResultSet to Object and from object Object Array
    By anmaston in forum What's Wrong With My Code?
    Replies: 4
    Last Post: April 7th, 2011, 06:11 AM
  4. Fill & sort an array
    By yroll in forum Collections and Generics
    Replies: 2
    Last Post: April 1st, 2010, 06:00 AM
  5. can't figure out how to sort an array.
    By etidd in forum Java Theory & Questions
    Replies: 2
    Last Post: February 6th, 2010, 03:07 PM