麻烦打印字符串数组的字典排序中首先出现的元素(java)

时间:2014-12-09 02:29:36

标签: java arrays string

我必须从键盘读取10个字符串,然后将它们保存到字符串数组中,最后我需要打印相对于字符串的字典排序的字符串。我在最后一部分遇到了麻烦?对我做错了什么的建议?

int size = 10;
int count = 0;
String[] words = new String[size];

Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter 10 digits: ");
while (count < size) {
    words[count] = keyboard.next();
    count++;
}
for (int i = 0; i < words.length; i++) {
    if (words[i].compareTo(words[i + 1]) > 0) {
        String biggest = words[i];

        System.out.println(biggest);
    }
}

1 个答案:

答案 0 :(得分:2)

要获得最小的(在词法排序中的第一个),你会这样做:

String smallest = null;

for (int i = 0; i < words.length; i++) {
    if (i == 0) {
        smallest = words[i];
    } else if (words[i].compareTo(smallest) < 0) {
        smallest = words[i]
    }
}

System.out.println(smallest);

或者,通过将数组转换为列表并使用Collections实用程序类:

String smallest = Collections.min(Arrays.asList(words));

或者,通过对数组进行排序并获取第一个值:

Arrays.sort(words);
String smallest = words[0];