【问题标题】:Sort strings in alphabetical order as they enter the array - Java在输入数组时按字母顺序对字符串进行排序 - Java
【发布时间】: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; 

          } 
        } 

      }

    }

这很好用,但我的教授需要在它输入数组“人”时对其进行排序,我不知道如何处理。任何建议/帮助都会很棒,谢谢!!!

这是我从教授那里收到的电子邮件:“要获得完整的学分,您必须在读入每个项目时将其插入到数组中的排序位置。不能全部读入并调用排序常规。”

【问题讨论】:

  • 与其比较两个四个循环,一个元素与另一个元素进行比较,不如考虑用用户输入替换其中一个循环。

标签: java arrays file sorting


【解决方案1】:

“我的教授需要在输入时对其进行排序”

这是一个链表,不是数组。

因此,您只能查看堆栈/队列(FILO/FIFO)中的当前项。

你是教授可能意味着按照输入的方式打印列表。

您可以通过将列表创建为队列来做到这一点。 Java 有一个可以使用的调用,称为Queue。还有StackLinkedList

【讨论】:

  • 您的解释很有道理,但这是我从教授那里收到的电子邮件:“要获得完整的信用,您必须在读取每个项目时将其插入数组中的排序位置。它不是可以全部阅读并调用排序例程。”所以我正在使用一个数组
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-21
  • 2013-12-21
相关资源
最近更新 更多