【发布时间】:2014-02-15 19:06:18
【问题描述】:
所以我有一个程序可以读取文件,将信息添加到数组中,然后使用交换排序按字母顺序对数组进行排序。问题是我误解了赋值,需要在输入数组时对字符串进行排序,而不是在输入后使用单独的排序方法。这是我所拥有的:
public class NumberCollection2
{
String nextName;
int nextNumber;
private Person[] people = new Person[50];
private int size =0;
public void load()
{
try
{
Scanner in = new Scanner(new File ("numbers.txt"));
while (in.hasNextLine())
{
nextName = in.next();
nextNumber = in.nextInt();
people[size]=new Person(nextName, nextNumber);
size++;
in.nextLine();
}
//use exchange sort to sort in ascending alphabetical order
int i, j;
for ( i = 0; i < size - 1; i++ )
{
for ( j = i + 1; j < size; j++ )
{
if ( people[ i ].getName().compareTo(people[ j ].getName()) > 0 )
{
Person temp = people [ i ];
people [ i ] = people [ j ];
people [ j ] = temp;
}
}
}
}
这很好用,但我的教授需要在它输入数组“人”时对其进行排序,我不知道如何处理。任何建议/帮助都会很棒,谢谢!!!
这是我从教授那里收到的电子邮件:“要获得完整的学分,您必须在读入每个项目时将其插入到数组中的排序位置。不能全部读入并调用排序常规。”
【问题讨论】:
-
与其比较两个四个循环,一个元素与另一个元素进行比较,不如考虑用用户输入替换其中一个循环。