Java获取用户输入的名字,姓氏,年龄,按字母顺序排序,然后按年龄排序

时间:2012-12-09 18:53:11

标签: java arrays arraylist

  

可能重复:
  Best way to sort 2 array lists?

package bubblesort;

import java.util.*;

public class BubbleSort {

public static void main(String[] args)
{
    Scanner input = new Scanner(System.in);
    Scanner input2 = new Scanner(System.in);
    List<String> lastnamesList = new ArrayList();
    List<String> firstnamesList = new ArrayList();
    List<Integer> ageList = new ArrayList();       
    List<String> fullnamesList = new ArrayList();
    int decider;
    String EOF = "EOF";


    System.out.println("Enter in 0 to sort by Last Name, Enter in 1 to sort by Age");
    decider = input.nextInt();

    /*if(decider == 0)
    {
    System.out.println("Sorting by Last Name");
        for(int i=0;i<3;i++)
        {
        System.out.println("Please Enter in your Last Name, FirstName, Age: " );
        fullnamesList.add(input2.nextLine());
        }
    Collections.sort(fullnamesList);
    System.out.println("Sorting by Last Name: ");
    System.out.println(fullnamesList);
    }*/ 
    //String[] lastnamesArray = lastnamesList.toArray(new String[lastnamesList.size()]);
    //String[] firstnamesArray = firstnamesList.toArray(new String[firstnamesList.size()]);
    if(decider == 1)
    {
    System.out.println("Sorting by Age");
        for(int i=0;i<3;i++)
        {
        System.out.println("Please Enter in your Last Name: " );
        lastnamesList.add(input2.nextLine());
        System.out.println("Please Enter in your First Name: " );
        firstnamesList.add(input2.nextLine());
        System.out.println("Please Enter in your Age: " );
        ageList.add(input.nextInt());

        }

    String[] firstnamesArray = firstnamesList.toArray(new String[firstnamesList.size()]);
    String[] lastnamesArray = lastnamesList.toArray(new String[lastnamesList.size()]);
    fullnamesList.addAll(firstnamesList);
    fullnamesList.addAll(lastnamesList);
    String[] fullnamesArray = fullnamesList.toArray(new String[firstnamesList.size()+lastnamesList.size()]);

    Collections.sort(fullnamesList);
    System.out.println("Sorting by Age");
    System.out.println(fullnamesList);
    }
}
public static void sortStringBubble(String x[])
{
    int j;
    boolean flag = true;
    String temp;

    while(flag)
    {
        flag = false;
        for(j = 0;j < x.length -1 ; j++)
        {
            if (x [j].compareToIgnoreCase(x[j+1])>0)
            {
                temp = x[j];
                x[j] = x[j+1];
                x[j+1] = temp;
                flag = true;
            }
        }
    }
}

}

我试图将名字,姓氏和年龄保持在一起,但我希望它按字母顺序排序为一个而不是单独排序。

1 个答案:

答案 0 :(得分:2)

而不是

List<String> lastnamesList = new ArrayList();
List<String> firstnamesList = new ArrayList();
List<Integer> ageList = new ArrayList();   

使用

List<Person> personList = new ArrayList<>();

其中Person是您自己编写的课程。比只有一个列表可以排序。

Person会有字段lastNamefirstNameage,因此他们将永远在一起。

另请参阅thisthis帖子,或these部分内容。