我正在尝试将“ args”按升序排序,我缺少什么?
每当我在命令行中放置随机参数时,前两个参数都会起作用,我会得到一个数组和一个字符串。但是,在第三篇文章中,我希望将数组按升序排序。输入始终为0。

我也尝试创建自己的算法,但效果不佳。

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] + " ");
    }*/
}
}


输出:

Printing as an array:
ball
cat
ship

Printing as a string;
ball cat ship

Printing after sorting;
[0, 0, 0]

最佳答案

我很确定这是您要执行的操作:

import java.util.Arrays;

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


作为程序参数,我输入了"abc" "efg" "abz",输出为

[abc, abz, efg]

Process finished with exit code 0

10-02 05:07