How to sort an array in Java

I have the following code. I want to sort by zip before I print. Any ideas?

import java.io.*;
import java.util.*;

public class ZipListList
{
      public static final int MAX = 25;
      
      public static void main (String[] args)
      {
      
            try
            {
            
                  Scanner scan = new Scanner (new File("Contacts.txt"));
                  Zip[] contacts = new Zip[MAX];
            
                  int count = 0;
            
                  //Read in contacts.dat file
                  while (scan.hasNext())
                  {
                        String firstname = scan.next();
                        String lastname = scan.next();
                        int zip = scan.nextInt();
      
                  //Loading each record into an array
                  
                        contacts[count] = new Zip (firstname, lastname, zip);
                        System.err.println(contacts[count]);
                        count++;
                  
                  }
                  
                  for (int index = 0; index < count; index++)
                        {      
                              System.out.println (contacts[index]);
                        }
                  
                        System.out.println ("\ntotal: " + count);
                  }
      
            catch (Exception except)
            
            {
                  System.err.println(except);
            }
      
      }

}
msheppard74Asked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
objectsConnect With a Mentor Commented:
try:

public int compare(Object o1, Object o2)
{
Sheppard78 r1 = (Sheppard78)o1;
Sheppard78 r2 = (Sheppard78)o2;
if (r1==null&&r2==null) return 0;
else if (r1==null) return 1;
else if (r2==null) return -1;
else return r1.getzipCode() - r2.getzipCode();
}
});
0
 
suprapto45Commented:
0
 
msheppard74Author Commented:
I tried this, still having problems

import java.io.*;
import java.util.*;

public class Sheppard78List
{
      public static final int MAX = 25;
      
      public static void main (String[] args)
      {
      
            try
            {
            
                  Scanner scan = new Scanner (new File("Contacts.txt"));
                  Sheppard78[] contacts = new Sheppard78[MAX];
            
                  int count = 0;
            
                  //Read in contacts.dat file
                  while (scan.hasNext())
                  {
                        String firstname = scan.next();
                        String lastname = scan.next();
                        int zip = scan.nextInt();
      
                  //Loading each record into an array
                  
                        contacts[count] = new Sheppard78 (firstname, lastname, zip);
                        System.err.println(contacts[count]);
                        count++;
                  
                  }
                  
                  Arrays.sort(contacts, new Comparator()
                  {
                        public int compare(Object o1, Object o2)
                        {
                              Sheppard78 r1 = (Sheppard78)o1;
                              Sheppard78 r2 = (Sheppard78)o2;
                              int result = r1.zip().compareTo(r2.zip());
                              if (result!=0)      
                              return result;
            }
          });

                  
                  //print it out to the screen (look in chapter 5 for this)
                  for (int index = 0; index < count; index++)
                        {      
                              System.out.println (contacts[index]);
                        }
                  
                        System.out.println ("\ntotal: " + count);
                  }
      
            catch (Exception except)
            
            {
                  System.err.println(except);
            }
      
      }

}
0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
suprapto45Commented:
compareTo is used for comparing objects. In your case, you are comparing primitive which is int. Either you have to change it to Integer or do not use compareTo.

Either

               Arrays.sort(contacts, new Comparator()
               {
                    public int compare(Object o1, Object o2)
                    {
                         Sheppard78 r1 = (Sheppard78)o1;
                         Sheppard78 r2 = (Sheppard78)o2;
                         Integer objInt1=new Integer(r1.zip());
                         Integer objInt2=new Integer(r2.zip());

                         int result = objInt1.compareTo(objInt2);
                         if (result!=0)    
                         return result;
            }
          });

Or

               Arrays.sort(contacts, new Comparator()
               {
                    public int compare(Object o1, Object o2)
                    {
                         Sheppard78 r1 = (Sheppard78)o1;
                         Sheppard78 r2 = (Sheppard78)o2;

                         int result = r1.zip() - r2.zip();
                         if (result!=0)    
                         return result;
            }
          });

I did not try it. Please try it and hopefully it works
0
 
msheppard74Author Commented:
I get the following errors

Sheppard78List.java:41: cannot find symbol
symbol  : method zip()
location: class Sheppard78
int result = r1.zip() - r2.zip();
               ^
Sheppard78List.java:41: cannot find symbol
symbol  : method zip()
location: class Sheppard78
int result = r1.zip() - r2.zip();
                          ^
Note: C:\Documents and Settings\Admin\My Documents\Java\Sheppard78List.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
2 errors
0
 
objectsCommented:
try:

               Arrays.sort(contacts, new Comparator()
               {
                    public int compare(Object o1, Object o2)
                    {
                         Sheppard78 r1 = (Sheppard78)o1;
                         Sheppard78 r2 = (Sheppard78)o2;
                         return r1.getZip() - r2.getZip();    // or whatever mehtod returns zip value
            }
          });
0
 
msheppard74Author Commented:
It's not sorting and I get an error println. THis is what it returns.

Kent          Brockman          12345
Charles          Burns                          24923
Cletus          Delroy                          25394
Ned          Flanders          4382
Seymour          Skinner                          45234
Homer          Simpson          62352
Milhouse          VanHouten          52352
Nelson          Muntz                          63265
Edna          Krabapple          72353
Jimbo          Jones                          10234
Martin          Prince                          2532
Patty          Bouvier                          23252
Troy          McClure                          32522
Marvin          Monroe                          10028
Waylon          Smithers          80214
Moe          Szyslak                          13095
Clancy          Wiggum                          23052
John          Frink                          20625
Barney          Gumbel                          11321
Julias          Hibbert                          13359
Lionel          Hutz                          21952
Helen          Lovejoy                          19202
java.lang.NullPointerException
0
 
suprapto45Commented:
>>"return r1.getZip() - r2.getZip();    // or whatever mehtod returns zip value"
objects is DEFINITELY right.

I thought that
r1.zip()

will return you the zip value as in your two previous comment you did not say that r1.zip() is error.
0
 
msheppard74Author Commented:
I changed to the method that returns the zip code. here is the new code. It does not return in zip order.

import java.io.*;
import java.util.*;

public class Sheppard78List
{
      public static final int MAX = 25;
      
      public static void main (String[] args)
      {
      
            try
            {
            
                  Scanner scan = new Scanner (new File("Contacts.txt"));
                  Sheppard78[] contacts = new Sheppard78[MAX];
            
                  int count = 0;
            
                  //Read in contacts.dat file
                  while (scan.hasNext())
                  {
                        String firstname = scan.next();
                        String lastname = scan.next();
                        int zip = scan.nextInt();
      
                  //Loading each record into an array
                  
                        contacts[count] = new Sheppard78 (firstname, lastname, zip);
                        System.err.println(contacts[count]);
                        count++;
                  
                  }
            
            Arrays.sort(contacts, new Comparator()
{
public int compare(Object o1, Object o2)
{
Sheppard78 r1 = (Sheppard78)o1;
Sheppard78 r2 = (Sheppard78)o2;
return r1.getzipCode() - r2.getzipCode();
}
});

                  //print it out to the screen (look in chapter 5 for this)
                  for (int index = 0; index < count; index++)
                        {      
                              System.out.println (contacts[index]);
                        }
                  
                        System.out.println ("\ntotal: " + count);
                  }
      
            catch (Exception except)
            
            {
                  System.err.println(except);
            }
      
      }

0
 
suprapto45Commented:
That is strange. I thought that it should work properly.

Okay, I'll have a look at it later on.

David
0
 
msheppard74Author Commented:
Here is the other class file so you can see all methods

import java.io.*;
import java.util.*;

public class Sheppard78
{
      String firstname, lastname;
      int zip;
      
      public Sheppard78 (String firstname, String lastname, int zip)
      {
            this.firstname = firstname;
            this.lastname = lastname;
            this.zip = zip;
      }
      
      public String toString()
      {
            return this.firstname + "  \t  " + this.lastname + "  \t  " + this.zip;
      }
      
      public void setfirstName (String firstname)
      {
            this.firstname = firstname;
      }
      
      public void setlastName (String lastname)
      {
            this.lastname = lastname;
      }
      
      public void setzipCode (int zip)
      {
            this.zip = zip;
      }
      
      public String getfirstName()
      {
            return this.firstname;
      }
      
      public String getlastname()
      {
            return this.lastname;
      }
      
      public int getzipCode()
      {
             return this.zip;
      }

}
0
 
objectsCommented:
>                     System.err.println(contacts[count]);

are you sure the output you're seeing is not the file as it is being read?
0
 
suprapto45Commented:
Hmm.....

Okay, please use the latest code from objects. Additionally, make sure that the Array.sort is executed. Add one line for debugging such as

System.out.println("Executing the Array.sort");
Arrays.sort(contacts, new Comparator()
{
 // all objects codes here
});

Please let me know whether System.out.println("Executing the Array.sort"); is executed or not
0
 
msheppard74Author Commented:
Much closer!! It's printing the non-sorted AND sorted. Any idea why?

Kent          Brockman          12345
Charles          Burns          24923
Cletus          Delroy          25394
Ned          Flanders          4382
Seymour          Skinner          45234
Homer          Simpson          62352
Milhouse          VanHouten          52352
Nelson          Muntz          63265
Edna          Krabapple          72353
Jimbo          Jones          10234
Martin          Prince          2532
Patty          Bouvier          23252
Troy          McClure          32522
Marvin          Monroe          10028
Waylon          Smithers          80214
Moe          Szyslak          13095
Clancy          Wiggum          23052
John          Frink          20625
Barney          Gumbel          11321
Julias          Hibbert          13359
Lionel          Hutz          21952
Helen          Lovejoy          19202
Martin          Prince          2532
Ned          Flanders          4382
Marvin          Monroe          10028
Jimbo          Jones          10234
Barney          Gumbel          11321
Kent          Brockman          12345
Moe          Szyslak          13095
Julias          Hibbert          13359
Helen          Lovejoy          19202
John          Frink          20625
Lionel          Hutz          21952
Clancy          Wiggum          23052
Patty          Bouvier          23252
Charles          Burns          24923
Cletus          Delroy          25394
Troy          McClure          32522
Seymour          Skinner          45234
Milhouse          VanHouten          52352
Homer          Simpson          62352
Nelson          Muntz          63265
Edna          Krabapple          72353
Waylon          Smithers          80214
0
 
msheppard74Author Commented:
It's this statement that's now printing in addition to the print statement in the for

System.err.println(contacts[count]); Why would this start printing all of a sudden?
0
 
suprapto45Commented:
>>"It's this statement that's now printing in addition to the print statement in the for "
So is the print statement in your "for next" executed? This should be the place where the ordered zip should be printed out.
0
 
objectsCommented:
> Much closer!! It's printing the non-sorted AND sorted. Any idea why?

becuase you print them first when loaded, then once sorted

> System.err.println(contacts[count]); Why would this start printing all of a sudden?

it always was :)
the sort was previously failing so it wasn't printing the sorted list
0
 
msheppard74Author Commented:
Lastly, what are these notes?

Note: C:\Documents and Settings\Admin\My Documents\Java\Sheppard78List.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

How do I handle them?
0
 
suprapto45Commented:
0
 
msheppard74Author Commented:
thanks for your help!
0
 
suprapto45Commented:
No problem...Glad we could help though I think that split is more appropriate here but never mind, we all are happy to help you

David
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.