我需要按字长将String数组排序到最小到最大的顺序。然后我需要打印出它们旁边的单词。
示例输出:
1:我,你,K
6:约瑟夫,删除
但我需要帮助排序数组。
代码:
package Objects;
import java.io.*;
import java.util.*;
import java.util.Arrays;
import java.lang.Object;
public class WordLength {
public static void main(String[] args) throws Exception{
Scanner scan = new Scanner(new File("wordlength.dat"));
int thresh = scan.nextInt(); //Scans the first integer
String[] array = new String[thresh]; //Creates an empty array with length of the threshold
for(int i = 0; i < array.length; i++) {
array[i] = scan.nextLine();
/* I need to sort the array from least to
greatest here so I can use the if statement
below.
*/
//Prints the word array from least to greatest by length
if(array[i].length() == i) {
System.out.print(i + ": " + array[i]);
}
}
}
}
答案 0 :(得分:0)
您可以使用自定义比较器对String
数组进行排序。例如
String [] arrr = {"World","Ho","ABCD"};
Arrays.sort(arrr,new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.length() - o2.length();
}
});
System.out.println(arrr[0]); \\ Output Ho
答案 1 :(得分:0)
重载之一接受Arrays.sort作为第二个参数,您可以在其中实现自己的自定义比较函数,以确定是否应将字符串放在另一个之前或之后,只需实现{{ 3}}方法。
答案 2 :(得分:-1)
我不用Java编码,但这个伪代码会起作用吗?
Grab the list of words.
Loop through them.
Get the length of the current word.
Add that word to that array number: a 5-letter word would go in array element 5.
Continue the loop until all the words have been added to the proper array.
Display each of the array elements.