Login with  Log in with facebook
Hiring Manager? SIGN UP HERE
2

take a list of numbers from command line, sort them ascending and print

Rishi Yadav
11/01/2011 at 16:53
2 Answers
1
3

This should work:

 

package sorting;

import java.util.Arrays;

public class integerArguments {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] numArray = convertToIntArray(args);
        Arrays.sort(numArray);
        for(int i=0; i< numArray.length; i++ )
            System.out.println(numArray[i]);       
    }
   
    private static int[] convertToIntArray(String[] stringArray)
    {
        int[] numArray = new int[stringArray.length];
        for (int i =0 ; i< stringArray.length ; i++)
        {
            try
            {
                numArray[i] = Integer.parseInt(stringArray[i]);
            }
            catch(Exception ex)
            {
                System.out.println("Cannot convert element number " + i);
            }
        }
        return numArray;
    }
}

Todd Reese
11/10/2011 at 10:17

2
1

A slightly shorter and considering numeric values not only ints.

 

package sorting;

import java.util.Arrays;

public class IntegerArguments {
    public static void main(String... args) {
        double[] allNumericArgs = new double[args.length];
        for (int i = 0; i < args.length; i++) {
            try {
                allNumericArgs[i] = Double.parseDouble(args[i]);
            } catch (NumberFormatException nfe) {
                System.out.println("element number "+i+" is not numeric assuming 0");
            }
        }
        System.out.println("before sorting:"+Arrays.toString(allNumericArgs));
        Arrays.sort(allNumericArgs);
        System.out.println("after sorting:"+Arrays.toString(allNumericArgs));
    }
}

 

Pravin Jain
01/26/2012 at 06:04

If you want to post any answer to this forum then you need to log in.
Schedule a Demo

Schedule a Demo with us

Name *
Email *
Phone *
Company *
Details