Solved

How to sort an array in Java

Posted on 2006-11-13
21
207 Views
Last Modified: 2010-03-31
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);
            }
      
      }

}
0
Comment
Question by:msheppard74
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 9
  • 8
  • 4
21 Comments
 
LVL 16

Expert Comment

by:suprapto45
ID: 17935095
0
 

Author Comment

by:msheppard74
ID: 17935136
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
 
LVL 16

Expert Comment

by:suprapto45
ID: 17935244
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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:msheppard74
ID: 17935298
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
 
LVL 92

Expert Comment

by:objects
ID: 17935335
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
 

Author Comment

by:msheppard74
ID: 17935356
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
 
LVL 16

Expert Comment

by:suprapto45
ID: 17935360
>>"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
 

Author Comment

by:msheppard74
ID: 17935400
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
 
LVL 16

Expert Comment

by:suprapto45
ID: 17935411
That is strange. I thought that it should work properly.

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

David
0
 

Author Comment

by:msheppard74
ID: 17935418
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
 
LVL 92

Expert Comment

by:objects
ID: 17935419
>                     System.err.println(contacts[count]);

are you sure the output you're seeing is not the file as it is being read?
0
 
LVL 92

Accepted Solution

by:
objects earned 500 total points
ID: 17935442
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
 
LVL 16

Expert Comment

by:suprapto45
ID: 17935464
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
 

Author Comment

by:msheppard74
ID: 17935469
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
 

Author Comment

by:msheppard74
ID: 17935475
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
 
LVL 16

Expert Comment

by:suprapto45
ID: 17935481
>>"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
 
LVL 92

Expert Comment

by:objects
ID: 17935483
> 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
 

Author Comment

by:msheppard74
ID: 17935492
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
 
LVL 16

Expert Comment

by:suprapto45
ID: 17935495
0
 

Author Comment

by:msheppard74
ID: 17935524
thanks for your help!
0
 
LVL 16

Expert Comment

by:suprapto45
ID: 17935540
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

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
null output 3 55
String array comparison 4 55
netbeans can not run self signed app 8 35
listing all the respondents to a twitter feed - Java 5 41
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses

738 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question