Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2006-10-30
16
Medium Priority
?
293 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
[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
  • 7
16 Comments
 
LVL 9

Accepted Solution

by:
matthew016 earned 2000 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
Build and deliver software with DevOps

A digital transformation requires faster time to market, shorter software development lifecycles, and the ability to adapt rapidly to changing customer demands. DevOps provides the solution.

 

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
 
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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses

722 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