【问题标题】:Sorting a tuple by variable按变量排序元组
【发布时间】:2014-02-09 01:02:47
【问题描述】:

我正在做以下活动: 目标是开发一个程序来管理成员列表 在跳远比赛中。可用名额为 15 个。 他们的数据将以与运动员相同的顺序引入 注册。 设计一个显示以下选项的程序:

1 – 注册参与者

2 – 列出所有参与者的数据

3 – 按标记列出所有参与者的数据

4 – 退出 如果选择1,将介绍其中一位参与者的数据: 名字,2012年最好成绩,2011年最好成绩,2010年最好成绩。

如果选择2,我们必须列出所有参与者的数据按背部排序 编号(他们注册的顺序)

如果选择 3,我们必须列出 2012 年之前排序的所有参与者的数据 标记,从大到小。

处理完每个选项后,必须再次显示主菜单, 直到选择选项4,退出程序。

我坚持按标记排序数据,这是我的程序,请问有什么想法吗?

package prc;

import epsa.Cio;

import java.util.Arrays;

import java.util.Collections;

import java.util.List;

public class Rrc2

{

    public static void main(String[] args)


    {

        int n=0;
        Tupla participants[]= new Tupla[15];
        while(true){    

        Cio.println("Choose what you would like to do");
        Cio.println("Type 1 to:Register a participant");
        Cio.println("Type 2 to:List all the participant's data");
        Cio.println("Type 3 to:List all the participants data by mark");
        Cio.println("Type 4 to:Quit");
    int i;

    i = Cio.readInt();

switch(i)
{
case 1:

    participants[n]= new Tupla();
    Cio.println("Insert dorsal number");
    participants[n].number = Cio.readInt();
    Cio.println("Insert participants name");
    participants[n].name = Cio.readString();
    Cio.println("Insert participants best mark for the year 2012");
    participants[n].bestMark2012 = Cio.readDouble(); 
    Cio.println("Insert participants best mark for the year 2011");
    participants[n].bestMark2011 = Cio.readDouble();
    Cio.println("Insert participants best mark for the year 2010");
    participants[n].bestMark2010 = Cio.readDouble();
    n++;



    break;

case 2:
    int t;

    for(t=0;t<15&&t<n;t++){ 

        Cio.println("name: " + participants[t].name);
        Cio.println("Dorsal number: " + participants[t].number);
        Cio.println("Best Mark 2012: " + participants[t].bestMark2012);
        Cio.println("Best Mark 2011: " + participants[t].bestMark2011);
        Cio.println("Best Mark 2010: " + participants[t].bestMark2010);
        Cio.println("//////////////////////////////////////////////////");
    }



    break;

case 3:

Collections.sort(participants);


break;

case 4:System.exit(0); 
break; 


default: 
    Cio.println("Not valid");

    break;


}
Cio.println("Press enter to continue");
Cio.readString();
}

    }
}

【问题讨论】:

  • 什么是prc.Tupla 对象?

标签: arrays list sorting collections tuples


【解决方案1】:

您只需要实现java.util.Comparator&lt;Tupla&gt; 并将其传递给您对Collections.sort() 的调用(并使用java.util.List 而不是数组)

Collections.sort(participants, new TuplaComparator());

您需要为TuplaComparator 实现(自己编写类)。它应该实现接口java.util.Comparator&lt;Tupla&gt;。 (参见 javadocs。)

变量participants 应该是一个ArrayList,而不是一个简单的数组,Collections.sort() 才能工作。

这有很多线索可以继续下去。我不会在我的答案中重现您的整个(家庭作业?)程序代码。

【讨论】:

  • 谢谢你的回答,我还是不明白你的回答,请你修改我的程序好吗?谢谢!
  • 如果您在程序中添加行号会有所帮助。
猜你喜欢
  • 2012-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-16
  • 2014-02-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多