Solved

How to sort an array in Java

Posted on 2006-11-13
21
202 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
  • 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
 

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
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
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

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

747 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

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now