从文件中读取数据并按整数排序?

时间:2013-08-04 14:20:45

标签: java string netbeans

我需要从包含字符串和整数的文件中读取数据,并用"#"的分隔符分隔。我需要按文件中的最后一个整数对行进行排序并打印出来吗?

   `public void displayTeams()throws IOException`
    `Scanner s = null;`
     `try {

s = new Scanner(new BufferedReader(new FileReader(" team.txt")));`

        while (s.hasNext()) { 
           System.out.println(s.next());
        }
     } 
     finally {
        if (s != null) {
           s.close();
        }
     }
  }`

然后文件看起来像: LIV#0#0#0#0#5#

MANB#0#0#0#0#7#

枝#0#0#0#0#1#

屁股#0#0#0#0#2#

洛尔#0#0#0#0#9#

教皇#0#0#0#0#0#

2 个答案:

答案 0 :(得分:1)

在此处使用已排序的集合,如TreeMap

// Sorted by key (last integer); value = complete line of text
Map<Integer, String> map = new TreeMap<Integer, String>();

String data = "hello#1#3#4#2#5#\n" +
              "world#1#3#4#2#\n" +
              "how is everybody?#1#3#4#"; // num of # can vary

// you'd read from a file instead
Scanner scanner = new Scanner(data).useDelimiter("#");

// process line by line
while (scanner.hasNextLine()) {
    String line = scanner.nextLine();

    // split every line &
    String[] split = line.split("#");
    // convert last int string to Int
    Integer last = Integer.valueOf(split[split.length - 1]);

    // save in the map
    map.put(last, line);
}

// iterate in sorted order
for (Map.Entry<Integer, String> entry : map.entrySet()) {
    System.out.println(entry.getValue());
}

输出

world#1#3#4#2#
how is everybody?#1#3#4#
hello#1#3#4#2#5#

答案 1 :(得分:0)

 ArrayList<String> stringList = new ArrayList<String>();
    ArrayList<Integer> intList = new ArrayList<Integer>();
    Scanner s = null; 
    try { 
        s = new Scanner(new BufferedReader(new FileReader("team.txt")));
    while (s.hasNext()) { 
        String tempStr = s.next();
       stringList.add(tempStr);
            int lastIndexOf = tempStr.lastIndexOf("#");
            String intStr = tempStr.substring(lastIndexOf-1, lastIndexOf);
            Integer parsedInt = Integer.parseInt(intStr);
            intList.add(parsedInt);
    }
    String lines[] = stringList.toArray(new String[stringList.size()]);
    Integer numbers[] = intList.toArray(new Integer[intList.size()]);
    boolean swapped = true;
    int j = 0;
   int tmp;
   String tmpS;
   while (swapped) {
    swapped = false;
    j++;
    for (int i = 0; i < numbers.length - j; i++) {
        if (numbers[i] > numbers[i + 1]) {
            tmp = numbers[i];
            tmpS = lines[i];
            numbers[i] = numbers[i + 1];
            lines[i] = lines[i + 1]; 
            numbers[i + 1] = tmp;
            lines[i + 1] = tmpS;
            swapped = true;
        }
    }
}

}

 finally {

    if (s != null) {
       s.close();
    }
 }