1

我从硬盘驱动器上的两个文件中获取输入:

studentNames.txt 和 studentScores.txt - 名称包含学生 ID 和姓名,而分数包含学生 ID 和分数。我已将数据放入两个 ArrayLists 中,并希望对数据进行排序,以便成绩转到匹配的 ID。

例如:

+------+--------------+---------+
|  ID  |     Name     |  Grade  |
+------+--------------+---------+
| 3305 | Smith Henry  | 92.0    |
| 5555 | Eddy Olivia  | 95.5    |
| 8915 | Johnson Luke | 98.5    |
+------+--------------+---------+

并且数据继续仅填充 ID / Grade - 我知道我需要使用 if 语句,但我将如何去做呢?

这是我的代码:

import java.util.*;
import java.io.*;

public class P_Supplemental_9 {

public static void main(String[] args) throws FileNotFoundException {
   File file1 = new File("c:/temp/studentNames.txt");
   File file2 = new File("c:/temp/studentScores.txt");

   if(file1.exists()) {
   Scanner input = new Scanner(file1);

   ArrayList<Student> students = new ArrayList();

   while(input.hasNext()) {
   students.add(new Student(input.nextInt(),input.nextLine()));
   }

   input.close();

   for(int o = 0;o < students.size();o++) {
   System.out.printf("%10d %20s avg\n", students.get(o).getStuId(),     students.get(o).getStuName());

   } // end for

   }

   if(file2.exists()) {
       Scanner input = new Scanner(file2);

       ArrayList<Student> grades = new ArrayList();

       while(input.hasNext()) {
           grades.add(new Student(input.nextInt(), input.nextLine()));

       } /// end while
       input.close();

   for(int o = 0;o < grades.size();o++) {

       System.out.printf("%10d %20s avg\n", grades.get(o).getStuId(), grades.get(o).getStuName());
   } // end for

   } // end if(file2.exists)





  } // end main method
 } // end P_Supplemental_9



class Student {
    private int stuId;
    private String stuName;
    private ArrayList <Double> grades;

    Student(int idIn, String nameIn) {

        this.stuId = idIn;
        this.stuName = nameIn;
       } // end student class

    Student(int idIn, ArrayList gradesIn) {
        this.stuId = idIn;
        this.grades = gradesIn;

    }

        public int getStuId() {
            return stuId;
        }

        /**
         * @param stuId the stuId to set
         */
        public void setStuId(int stuId) {
            this.stuId = stuId;
        }

        /**
         * @return the stuName
         */
        public String getStuName() {
            return stuName;
        }

        /**
         * @param stuName the stuName to set
         */
        public void setStuName(String stuName) {
            this.stuName = stuName;
        }

        /**
         * @return the grades
         */
        public ArrayList getGrades() {
            return grades;
        }

        /**
         * @param grades the grades to set
         */
        public void setGrades(ArrayList grades) {
            this.grades = grades;
        }

} // end student class

这是来自 Studentnames.txt 的数据

3305 Smith Henry
5555 Eddy Olivia
8915 Johnson Luke

这是来自 Studentscores.txt 的数据

3305 92.0
5555 95.5
8915 98.5
3305 89.0
5555 90.5
8915 95.5
3305 78.5
5555 85.0
8915 82.0
4

5 回答 5

2

您可以使用Collections#sort(List, Comparator)对两个列表进行排序。

假设他们是学生和他们的分数之间的一对一关系,这将允许您获取学生和分数以及列表的每个元素。

我会想象它看起来像这样。

Collections.sort(studentNames, new Comparator<Student>() {
    public int compareTo(Student o1, Student o2) {
        return o1.getStuId() - o2.getStuId();
    }
});

这将为您提供List按学生 ID 排序的学生。

然后,您将使用相同的概念对分数列表进行排序。一旦你有了它,这两个列表现在应该按学生 ID 顺序排列,你应该能够遍历它们。

另一个想法是将学生和分数存储在Map学生 ID 的键控中。

然后,您将能够迭代地图的键并根据这些 ID 提取每个学生并评分

已更新以满足要求

阅读更新后的要求后,我注意到最好使用排序地图而不是列表。

基本上,我们将每个学生的姓名放入一个以个人 ID 为关键字的排序映射中。然后,我们将每一个都放在一个排序地图中的一个列表中,该地图以 ID 为键

public class TestArraySort {

    public static void main(String[] args) {
        new TestArraySort();
    }

    public TestArraySort() {

        try {
            File file1 = new File("studentNames.txt");
            File file2 = new File("studentScores.txt");

            // Better to check for both files here, other wise it's just wasting time
            if (file1.exists() && file2.exists()) {
                // Create the sorted maps so that they are in scope...
                Map<Integer, String> mapStudents = new TreeMap<Integer, String>();
                Map<Integer, List<Double>> mapScores = new TreeMap<Integer, List<Double>>();

                Scanner input = null;
                try {
                    input = new Scanner(file1);
                    // Read the student information...
                    while (input.hasNext()) {
                        int id = input.nextInt();
                        String name = input.nextLine().trim();
                        mapStudents.put(id, name);
                    }
                    // Safty net
                } finally {
                    input.close();
                }

                try {
                    // Read the scores
                    input = new Scanner(file2);
                    while (input.hasNext()) {
                        int id = input.nextInt();
                        double score = input.nextDouble();

                        // If the list doesn't already exist, create it
                        List<Double> scores = mapScores.get(id);
                        if (scores == null) {
                            scores = new ArrayList<Double>(25);
                            mapScores.put(id, scores);
                        }
                        scores.add(score);
                    } /// end while
                    // Safty net
                } finally {
                    input.close();
                }

                // Dump the results
                System.out.println("+------------+----------------------+------+");
                for (Integer id : mapStudents.keySet()) {
                    // Display the student results
                    String name = mapStudents.get(id);
                    System.out.printf("| %10d | %-20s | ", id, name);
                    List<Double> scores = mapScores.get(id);
                    if (scores.size() > 0) {

                        // Sort the list
                        Collections.sort(scores);
                        // Reverse the list so that the scores are now in order from highest to lowest
                        // Sure, I could create a reverse comparator when I sort it, but
                        // I'm lazy...
                        Collections.reverse(scores);

                        // Print the first score...
                        System.out.printf("%4.1f |\n", scores.get(0));
                        // Print the remaining scores...
                        for (int index = 1; index < scores.size(); index++) {
                            System.out.printf("| %10s | %-20s | %4.1f |\n", "", "", scores.get(index));
                        }

                    } else {

                        System.out.println("00.0 |");

                    }
                    System.out.println("+------------+----------------------+------+");

                }

            } // end if(file2.exists)    }

        } catch (IOException exp) {
            exp.printStackTrace();
        }
    }
}

哪个生产

+------------+----------------------+------+
|       3305 | Smith Henry          | 92.0 |
|            |                      | 89.0 |
|            |                      | 78.5 |
+------------+----------------------+------+
|       5555 | Eddy Olivia          | 95.5 |
|            |                      | 90.5 |
|            |                      | 85.0 |
+------------+----------------------+------+
|       8915 | Johnson Luke         | 98.5 |
|            |                      | 95.5 |
|            |                      | 82.0 |
+------------+----------------------+------+
于 2012-10-29T02:02:45.323 回答
0
File one data
abc
abcd
bcd

file two data
abc
abcd 
bcd
cdf


final resutlt

abc
abc 
abcd
abcd
bcd
bcd
cdf



package com.ravisoft.logic;
/*
String tempDataArray[] =
    StringUtils.split(mergeStr, Utils.LINE_SEPARATOR);
java.util.Arrays.sort(tempDataArray);

String data = StringUtils.join(tempDataArray, Utils.LINE_SEPARATOR, 0);*/

import java.util.ArrayList;
import java.util.Collections;
import java.io.*;

public class ReadDemo
{
    public static void main(String args[]){
        ArrayList<String> fileData = new ArrayList<String>();
        String fileName1 = "E:\\ROUTINE_WORK\\MAY_ROUTINE_WORK\\MAY282013\\New1.TXT";
        String fileName2 = "E:\\ROUTINE_WORK\\MAY_ROUTINE_WORK\\MAY282013\\New2.TXT";
        int lines = 0;
        try 
        {
          // set up input stream1
        FileReader fr1 = new FileReader(fileName1);
          // buffer the input stream
        BufferedReader br1 = new BufferedReader(fr1);

          // set up input stream2
        FileReader fr2 = new FileReader(fileName2);
          // buffer the input stream
        BufferedReader br2 = new BufferedReader(fr2);

          // read and display1
        String buffer1 = "";



        while ((buffer1 = br1.readLine()) != null)
        {
          fileData.add(buffer1);

          System.out.println("First file: "+buffer1);  // display the line
          ++lines;
        }

      br1.close();

        String buffer2 = "";


            while ((buffer2 = br2.readLine()) != null) 
            {
                  fileData.add(buffer2);

                  System.out.println("Second file: "+buffer2);  // display the line
                  ++lines;
            }

      br2.close();
    System.out.println("Total lines before sorting: "+lines);
    lines=0;
      Collections.sort(fileData);


      System.out.println("Sorted list");
      System.out.println();
      System.out.println();
      System.out.println();
      System.out.println();
      System.out.println();

        for(String s : fileData) {
            ++lines;
          System.out.println(s);
        }
        System.out.println("Total lines after sort: "+lines);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

      }

}
于 2013-05-28T08:07:22.013 回答
0

Comparable您的class. 现在您可以轻松调用Collections.sort(studentNames)(假设studentNames是 a List

于 2012-10-29T02:07:26.500 回答
0

如果您尝试比较来自不同 arrayLists 的两个值,假设它们是字符串值

if (array1.get(i).toString().compareTo(array2.get(j).toString()) == 0)

于 2012-10-29T01:59:02.320 回答
0

我认为最好的方法是使用Map. 在阅读任一文件时,将学生 ID 映射到与其关联的数据(姓名或考试成绩)。然后,遍历学生 ID 的集合,分别用nameMap.get(id)和获取姓名和分数scoreMap.get(id)- 其中每个id都是 ID 集合的一个元素,可通过 获取nameMap.keySet()

于 2012-10-29T02:04:45.597 回答