reordering an array


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 2 of 2

Thread: reordering an array

  1. #1
    Join Date
    Jun 2004
    Posts
    1

    reordering an array

    I'm trying to compare the elements in an string array to an incoming string value. If this method is called, the string value must always be in rs[0] in the new array like so:

    rs[0] = "INSERT DT, NPA, NXX";
    rs[1] = "EFF DT, NPA, NXX";
    rs[2] = "NPA, EFF DT";
    rs[3] = "DUMMY SORT 1";

    public String[] keepSortBy()
    {
    try
    {
    String strCurrSort = "INSERT DT, NPA, NXX";

    String[] ds = new String[4];
    ds[0] = "EFF DT, NPA, NXX";
    ds[1] = "NPA, EFF DT";
    ds[2] = "INSERT DT, NPA, NXX";
    ds[3] = "DUMMY SORT 1";
    String[] rs = new String[ds.length];
    for (int i = 0; i < ds.length - 1; i++)
    {

    if (!ds[i].equals(strCurrSort))
    {
    rs[0] = strCurrSort;
    rs[i + 1] = ds[i];
    } else
    {
    rs[0] = strCurrSort;
    rs[i + 1] = ds[i + 1];
    }

    }
    return rs;
    } catch (Exception e)
    {
    System.out.println("Error in keepSortBy: " + e.toString());
    return null;
    }

    }
    If the declaration of the ds array is changed to 3 and the appropriate elements are declared ds[0] - ds[2], the above method works every time no matter where the match occurs in the incoming array.

    Any suggestions?

    Thanks

  2. #2
    Join Date
    Apr 2004
    Posts
    100
    the problem is in the line

    rs[i + 1] = ds[i];

    if both arrays are defined to have 4 elements,
    then when i is 3,

    rs[i+1] would be invalid because rs only goes from 0 to 3.

    that also explains why it works if the size of ds is 3, because i + 1 stays within 0 and 3

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center