Header javaperspective.com
JavaPerspective.com  >   Beginner Tutorials  >   5. Java in Practice  >   5.8. Java code exercises  >   5.8.6. Code exercise 6

5.8.6. Code exercise 6
Last updated: 27 January 2013.

Create a class named Practice and write a method named sortArguments(String[] args) that prints the command-line arguments to the standard output in alphabetical order. The App class shown below contains a main method that calls the method sortArguments(String[] args) as follows:

public final class App {

   
public static void main(String[] args) {
         
new Practice().sortArguments(args);
   
}

}

For example, if the user enters the following command:

java App Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune Pluto

The output must be the following:

Earth
Jupiter
Mars
Mercury
Neptune
Pluto
Saturn
Uranus
Venus



import java.util.Arrays;

public final class Practice {

   
public void sortArguments(String[] args){
         
Arrays.sort(args);

         
for(String s : args)
               
System.out.println(s);
   
}

}

As you can see, I used the class Arrays since it provides a method that meets my needs. Note that in a method signature, you can declare an array argument with a series of 3 dots instead of the opening and closing square brackets. Such an array must be the last argument if there are several arguments in the method's signature. As an example, you can change the signature of the method sortArguments like this:

import java.util.Arrays;

public final class Practice {

   
public void sortArguments(String... args){
         
Arrays.sort(args);

         
for(String s : args)
               
System.out.println(s);
   
}

}


You are here :  JavaPerspective.com  >   Beginner Tutorials  >   5. Java in Practice  >   5.8. Java code exercises  >   5.8.6. Code exercise 6
Next tutorial :  JavaPerspective.com  >   Beginner Tutorials  >   5. Java in Practice  >   5.8. Java code exercises  >   5.8.7. Code exercise 7

Copyright © 2013 - 2016. JavaPerspective.com. All rights reserved.  ( Terms | Contact | About ) 
Java is a trademark of Oracle Corporation
Image 1 Image 2 Image 3 Image 4 Image 5 Image 6 Image 7