【发布时间】:2015-04-08 20:44:07
【问题描述】:
好的,所以我需要列出未排序的单词:
freddy
at
elephant
whoooooodat
alice
tommy
bobby
it
at
about
并按长度和字母顺序对其进行排序:
at
at
it
about
alice
bobby
tommy
freddy
elephant
whoooooodat
我可以用 Collections.sort(words) 对其进行排序并得到:
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;
}
}
如果你能帮助我,那就太好了……
【问题讨论】:
-
您的
compareTo(...)方法比较值的长度,这意味着您的列表将按大小排序,而不是按字母顺序。
标签: java arrays sorting arraylist