Solved

Java5: Sort and print out names (user inputs) alphabetically

Posted on 2006-10-30
16
273 Views
Last Modified: 2008-02-01
Dear experts:

Hi again!

I am trying to write a simple code to get  client names from clients, and alphabetically sort and print out them.

The code (as it is) is very poor, and requires a tremendous improvement. I really like to learn how to write a code which is best functioning and most professional (?).

Hope you experts may kindly help me with tghe code.

Thanks a lot!



--------------------- Here is my very poor code --------------------------------------------------------------------------
iimport javax.swing.*;


public class java
{
  static void main (String[] args)
  {
      java duta = new java ();
      duta.sortNames ();
      System.exit (0);
  }
 
   
  public String [] getNames ()
  {
    int max = 7;
   
   
    String [] names = new String [max];
   
    int i;
    for (i = 1; i <= max; i++ )
    {
       names[i] = getInput ("Enter a name.");  // get seven names from users.

     }
   
    return names;    


 }
     
     
   
  public String getInput (String msg)
  {
    String name = JOptionPane.showInputDialog (msg);
    return name;
  }
 
  public void sort_outputNames ( )
  {
    String [] names = getNames ();  // codes to alphabetically sort names
   
   
   display (sorted names) // display sorted names

  }
 
  }
 
 
   
 
 
 
  public void display (String msg)
  {
     JOptionPane.showMessageDialog (null, msg);    
  }
 
 
 
 
}
 
 
   
   
 
 
0
Comment
Question by:duta
  • 9
  • 7
16 Comments
 
LVL 9

Accepted Solution

by:
matthew016 earned 500 total points
ID: 17838789
Some quick comments :

1)
In Java we use to name a class with an upper case letter.
So instead of java, make it Java.

2)
This class need a main method if u want to be able to run it,
I can see in your code :

  static void main (String[] args)
  { [...] }

But it must be

  public static void main (String[] args)
  { [...] }

That's a convention as well for a class to be able to run.

3)
This code throws an exception :

    int max = 7;
   
   
    String [] names = new String [max];
   
    int i;
    for (i = 1; i <= max; i++ )
    {
       names[i] = getInput ("Enter a name.");  // get seven names from users.

     }

U specify an array of size 7 : so u can put a value in case 0, 1, 2, 3 , 4, 5, 6 in the array.

Look at what u are doing in the loop :
U don't put any values in array 0, and u put values in 1,2,3,4,5,6,7,8 but thius will throw u an ArrayIndexOutOfBoundsException since there is no "8".

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
      at java.getNames(java.java:24)
      at java.sortNames(java.java:43)
      at java.main(java.java:9)
0
 
LVL 9

Expert Comment

by:matthew016
ID: 17838808
Let me correct one sentence :

"U don't put any values in array 0, and u put values in 1,2,3,4,5,6,7,8 but thius will throw u an ArrayIndexOutOfBoundsException
since there is no "8"."

must be

"U don't put any values in array 0, and u put values in 1,2,3,4,5,6,7 but thius will throw u an ArrayIndexOutOfBoundsException
since there is no "7".
But only from 0 to 6
0
 
LVL 9

Expert Comment

by:matthew016
ID: 17838851
Here is your code improved :

import java.util.Arrays;
import javax.swing.JOptionPane;
public class Java
{
  public static void main (String[] args)
  {
      Java duta = new Java ();
      duta.sortNames ();
  }
  public String [] getNames ()
  {
    int max = 7;
    String [] names = new String [max];
    int i;
    for (i = 0; i < max; i++ )
    {
       names[i] = getInput ("Enter a name.");  // get seven names from users.
     }
    return names;    
 }
  public String getInput (String msg)
  {
    String name = JOptionPane.showInputDialog (msg);
    return name;
  }
  public void sortNames ( )
  {
    String [] names = getNames ();  // codes to alphabetically sort names
    Arrays.sort(names);
    display (names); // display sorted names
  }
  public void display (String [] names)
  {
     JOptionPane.showMessageDialog (null, names);
  }
}
0
 

Author Comment

by:duta
ID: 17838896
Dear Matthew:
You are a genuius. That is awesome.

By the way, may I ask a quick question?

How may I print out the names that comes first and last in the sorted names?

Thanks!
0
 
LVL 9

Expert Comment

by:matthew016
ID: 17838919
JOptionPane.showMessageDialog (null, names[0]+"\n"+names[names.length-1]);
0
 

Author Comment

by:duta
ID: 17838954
Dear Matthew:

Thanks a lot.

By the way, I wonder whether I may use IgnoreCase or ToLowerCase.

Thanks!
0
 

Author Comment

by:duta
ID: 17838958
When I tried John, john, King, and king, they were sorted not as I expected.

Thanks!
0
 
LVL 9

Expert Comment

by:matthew016
ID: 17838966
Case sensitive :
java.util.Arrays.sort(myArray);

Case insensitive :
java.util.Arrays.sort(myArray, String.CASE_INSENSITIVE_ORDER);
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 9

Expert Comment

by:matthew016
ID: 17838994
For more professional code, be more oriented objected.

Create a class Client, create a class that contains a list of Clients, and a Test class.
Maybe it is a bit too much for this simple code.

For example :
*************************************************************
public class Client {
      private String name;
      
      public Client(String name) {
            this.name = name;
      }
      public String getName() {
            return name;
      }
      public String toString() {
            return name;
      }
}
*************************************************************
import java.util.ArrayList;
import java.util.Collections;

public class Clients {
        private ArrayList clients;
        
        public Clients() {
              clients = new ArrayList();
        }
        public void addClient(Client client) {
              clients.add(client);
        }
        public ArrayList getClients () {
                return clients;    
        }
        public void sortNames () {
          Collections.sort(clients);
        }
}
*************************************************************
import javax.swing.JOptionPane;

public class Test {
        public static int MAX = 7;
        private Clients clients;
        
        public Test() {
              makeClients();
              sortClients();
              displayClients();
        }
        private void makeClients () {
            clients = new Clients();
          for (int i = 0; i < MAX; i++ ) {
             Client client = new Client(getInput ("Enter a name."));  
                                            // get seven names from users.
             clients.addClient(client);
           }
        }
        private String getInput (String msg) {
              return JOptionPane.showInputDialog (msg);
        }
        private void sortClients() {
              clients.sortNames();
        }
        private void displayClients () {
           JOptionPane.showMessageDialog (null, clients.getClients());
        }
        public static void main (String[] args) {
            new Test();
        }
}
0
 

Author Comment

by:duta
ID: 17839000
Dear Matthew:

I tried as the follows, but I got some error messages.

Thanks again!

_____________________________   The modified area __________________________


public void sortNames ( )
  {
    String [ ] names = getNames ( );  
 
   //  Arrays.sort(names);
   
   java.util.Arrays.sort(names, String.CASE_INSENSITIVE_ORDER);  // This is a new addition

   
    display (names);
    JOptionPane.showMessageDialog
                     (null, "The fist name is " 
                          + names [0]
                          + ".\n The last name is " 
                          +names [names.length - 1] );
       
  }
0
 
LVL 9

Expert Comment

by:matthew016
ID: 17839009
What is the error ?

Why can't u debug that yourself ?
0
 

Author Comment

by:duta
ID: 17839020
Sorry to bother you too much.

I asked you because I could not do it.

I think you did enough for me tonight. Regardless of answering my last question, I am going to accept your tip as acceptable solution.

Thanks again!
0
 
LVL 9

Expert Comment

by:matthew016
ID: 17839030
Hey duta, u are not bothering me at all !!!

I want to help u and know why u can't see the new problem by yourself !!!

If u can see your problems everything will be much easier !

My last comment could be interpreted differently, sorry !
0
 

Author Comment

by:duta
ID: 17839031
The error message was :

"cannot find
symbol
variable util
Location: class Java

Thanks!
0
 
LVL 9

Expert Comment

by:matthew016
ID: 17839040
ok, I think that's because u imported java.util

and u put in the code :

 java.util.Arrays.sort(names, String.CASE_INSENSITIVE_ORDER);

If u imported java.util u just need to code this :

Arrays.sort(names, String.CASE_INSENSITIVE_ORDER);
0
 

Author Comment

by:duta
ID: 17839064
Thank so much for helping me out so kindly and patiently.

It works just great.

I am a real beginner, but I am working hard to learn.

Thanks again!
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
eclipse formatting 6 73
egit plugin on eclipse 8 40
xampp tool 12 28
java stored proc example 9 23
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…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
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…

867 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

17 Experts available now in Live!

Get 1:1 Help Now