Simple Bubble Sort using strings

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Bubbs
    New Member
    • Nov 2007
    • 17

    Simple Bubble Sort using strings

    Hi,
    I have to sort customer names in a customer class i have created. Now, there is a method called getName() that basically returns the string name stored in an instance variable of the customer class.
    This is a bubble sort method I have written. I really cant figure out why this throws a runtime null pointer exception at the IF statement which compares the strings. Please help.

    [CODE=java]private Customer[] bubbleSort(Cust omer c[])
    {
    boolean swaped = true;
    Customer temp;

    if (c != null)
    {
    while(swaped)
    {
    swaped = false;

    for (int i = 0; i < c.length - 1; i++)
    {
    if (c[i].getName().comp areTo(c[i + 1].getName()) > 0)
    {
    temp = c[i];
    c[i] = c[i + 1];
    c[i + 1] = temp;
    swaped = true;
    }
    }
    }
    }
    return c;
    }[/CODE]

    Thanks
    Last edited by Ganon11; Mar 13 '08, 03:57 PM. Reason: Please use the [CODE] tags provided.
  • Bubbs
    New Member
    • Nov 2007
    • 17

    #2
    Same Null pointer exception at the printArray(), that prints the toString of each object in the array to a JTextArea called infoArea. The exception is at the line
    infoArea.setTex t(c[i].toString());

    Heres the code
    private void printArray(Cust omer c[])
    {
    if (c != null)
    {
    for(int i = 0; i < c.length; i++)
    {
    infoArea.append (c[i].toString());
    }
    }
    }
    Thanks

    Comment

    • JosAH
      Recognized Expert MVP
      • Mar 2007
      • 11453

      #3
      Well, the at least one of your c[i] elements is null and the error must be found
      somewhere else.

      kind regards,

      Jos

      Comment

      • r035198x
        MVP
        • Sep 2006
        • 13225

        #4
        Yep, either one of the c[i]s is null or infoArea itself is null.
        You could print each of them before you "dot" them to catch the culprit.

        Comment

        • Bubbs
          New Member
          • Nov 2007
          • 17

          #5
          thanks guys, much appreciated.

          Comment

          • BigDaddyLH
            Recognized Expert Top Contributor
            • Dec 2007
            • 1216

            #6
            Please enclose your posted code in [code] tags (See How to Ask a Question).

            This makes it easier for our Experts to read and understand it. Failing to do so creates extra work for the moderators, thus wasting resources, otherwise available to answer the members' questions.

            Please use [code] tags in future.

            MODERATOR

            Comment

            Working...