简体   繁体   中英

How do I sort args into ascending order?

I am trying to sort 'args' into ascending order, what am I missing? Whenever I put random arguments in the command line the first two will work, I get an array and a string. However, on the third one I want the array to be sorted into ascending order. The input is always 0.

I also tried to create my own algorithm but it dint' work.

import java.util.Arrays;

public class tri {

public static void main (String[] args) 
{
    if (args.length < 3) {
        System.out.println("Re-execute with at least 3 arguments");
        System.exit(-1);
    }

    System.out.println("\n Printing as an array:");

    for (int i=0; i < args.length; i++)     //print each word 
        System.out.println(args[i]);

    String str = "";

    for (int i=0; i < args.length; i++) 
        str = str + args[i] + " ";          //concatenate into a string

    System.out.println("\n Printing as a string:");

    System.out.println(str);                //print the string


    System.out.println("\n Printing after sorting:");


     int [] sorted = new int[args.length];
     Arrays.sort(sorted);                   //sort the sorted array
     System.out.println(Arrays.toString(sorted));

    /*for (int i=0; i < args.length - 1; i++)  {
        System.out.print(args[i] + " ");  
    }*/
}
}

Output:

Printing as an array:
ball
cat
ship

Printing as a string;
ball cat ship

Printing after sorting;
[0, 0, 0]

I'm pretty sure this is what you're trying to do:

import java.util.Arrays;

public class Tri {
    public static void main(String[] args) {
        Arrays.sort(args);
        System.out.println(Arrays.toString(args));
    }
}

As program arguments I entered "abc" "efg" "abz" and the output was

[abc, abz, efg]

Process finished with exit code 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM