如何将int sort切换为String排序?

use*_*152 1 java sorting list

我编写了一些代码来排序用户输入的随机整数.如何将其切换为随机输入的字母排序?Aka,用户输入j,s,g,w,程序输出g,j,s,w?

for (int i = 0; i < random.length; i++) { //"random" is array with stored integers
                // Assume first value is x
                x = i;
                for (int j = i + 1; j < random.length; j++) {
                    //find smallest value in array (random)
                    if (random[j] < random[x]) {
                        x = j;
                    }
                }
                if (x != i) {
                    //swap the values if not in correct order
                    final int temp = random[i];
                    random[i] = random[x];
                    random[x] = temp;
                }
                itsATextArea.append(random[i] + "\n");// Output ascending order
            }
Run Code Online (Sandbox Code Playgroud)

最初我希望(虽然我知道我正确的机会对我不利)用"字符串"替换所有'int'会起作用......自然我错了,意识到我可能要列出之前的字母是什么通过使用list.add("a")等列表; 等等

我很抱歉,如果这似乎我要求你们做所有的工作(我不是),但我不完全确定如何开始这个,所以如果有人可以提供一些提示或技巧,那将是非常感谢!

mrc*_*ori 5

你可以使用String.compareTo()来做到这一点:

改变这个:

int[] random = new int[sizeyouhad];
...
if (random[j] < random[x]) {
...
final int temp = random[i];
Run Code Online (Sandbox Code Playgroud)

至:

String[] random = new String[sizeyouhad];
...
if (random[j].compareTo(random[x]) < 0) {
...
final String temp = random[i];
Run Code Online (Sandbox Code Playgroud)

试用你的代码:

String[] random = new String[3];
random[0] = "b";
random[1] = "c";
random[2] = "a";
int x = 0;
//"random" is array with stored integers
for (int i = 0; i < random.length; i++) { 
    // Assume first value is x
    x = i;
    for (int j = i + 1; j < random.length; j++) {
        //find smallest value in array (random)
        if (random[j].compareTo(random[x]) < 0) {
            x = j;
        }
    }
    if (x != i) {
        //swap the values if not in correct order
        final String temp = random[i];
        random[i] = random[x];
        random[x] = temp;
    }
    System.out.println(random[i] + "\n");// Output ascending order
}
Run Code Online (Sandbox Code Playgroud)