好的所以我需要列出未分类的单词:
freddy
at
elephant
whoooooodat
alice
tommy
bobby
it
at
about
按长度和字母顺序排序:
at
at
it
about
alice
bobby
tommy
freddy
elephant
whoooooodat
我可以使用Collections.sort(单词)对其进行排序并获取:
at
it
at
alice
tommy
bobby
about
freddy
elephant
whoooooodat
我只需要帮助按字母顺序排列。
继承我目前的代码:
public class Lab1
{
public static void main( String args[] ) throws IOException
{
Scanner file = new Scanner(new File("lab1.dat"));
ArrayList<Word> words = new ArrayList<Word>();
while(file.hasNext())
{
//add in a new Word to words
words.add(new Word(file.next()));
}
//can sort the words with this
Collections.sort(words);
//make letter lower case and compare asii values
// need to sort the words by alphabetically
/*
for (int i = 0; i < words.size()-1 ; i++)
{
int min = i;
for(int j= i+1; j < words.size(); j++){
String minstring = (String)words.get(min);
if((((String)words.get(min)).toLowerCase()).compareTo(words.get(j)) > 0)
min =j;
}// end of inner loop
if (min!= i){
Word temp = words.get(min);
words.set(min,words.get(i));
words.set(i,temp);
}// end of sort if
} //end of outer loop
*/
//print out words
for (int j =0; j < words.size(); j++)
System.out.println(words.get(j));
}
}
//Second Part
public class Word implements Comparable<Word>
{
private String word;
//constructors
public Word()
{
word = "";
}
public Word(String a)
{
word =a;
}
//compareTo
public int compareTo(Word other)
{
/*if (word.equals(other))
{
if((word.charAt(0)).toLowerCase() )
}*/
return word.length() - other.word.length();
}
public String toString()
{
return word;
}
}
如果你能帮助我那会很棒......
答案 0 :(得分:2)
public class MyComparator implements Comparator<String>{
@Override
public int compare(String o1, String o2) {
if (o1.length() > o2.length()) {
return 1;
} else if (o1.length() < o2.length()) {
return -1;
}
return o1.compareTo(o2);
}
}
然后:
Collections.sort(yourList, new MyComparator());
答案 1 :(得分:0)
您的比较方法还应按字母顺序实现:
public int compareTo(Word other)
{
int difference = word.length() - other.word.length();
if(difference == 0){
return word.compareToIgnoreCase(other.word);
else{
return difference;
}
}