不好意思各位,一开始问题没表述明白,已经做了修改。
问题:范围数据 562 ~602 928 ~968 671 ~711 819 ~859 302 ~342 532 ~572 958 ~998 453 ~493 671 ~711 193 ~233 931 ~971 54 ~94 349 ~389 775 ~815现为原程序中要处理的数据,数据放在代码中不方便,想把这些数据放在文件rang-file.txt中,通过文件读取的方式让程序来处理这些数据。对下面原程序做下修改,使输出结果一样。
原程序如下:
package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
public class NumricRange {
public static void main(String[] args) throws Exception {
int[] numrics = new int[1000];
File file = new File("range-file.txt");
PrintStream out = new PrintStream(file);
//要处理的数据
out.println("562 ~602 928 ~968 671 ~711 819 ~859 302 ~342 532 ~572 958 ~998");
out.println("453 ~493 671 ~711 193 ~233 931 ~971 54 ~94 349 ~389 775 ~815");
out.close();
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
String[] groups = line.split("[\t ]+(?!~)");
if (groups != null)
for (String group : groups) {
String[] ranges = group.split("[\t ]*~");
int min = Integer.parseInt(ranges[0]);
int max = Integer.parseInt(ranges[1]);
for (int i = min; i <= max; i++)
numrics[i]++;
}
}
TreeMap<Integer, List> result = new TreeMap<>();
int lastTimes = -1;
int[] lastResult = null;
for (int i = 0; i < 1000; i++) {
int time = numrics[i];
if (time == lastTimes)
lastResult[1] = i;
else if (time > -1) {
List list = result.get(time);
if (list == null) {
list = new ArrayList();
result.put(time, list);
}
list.add(lastResult = new int[] { i, i });
lastTimes = time;
}
}
Iterator<Entry<Integer, List>> it = result.entrySet().iterator();
while (it.hasNext()) {
Entry<Integer, List> entry = it.next();
int time = entry.getKey();
List<int[]> list = entry.getValue();
System.out.println("出现" + time + "次的范围:");
for (int[] range : list) {
System.out.print(range[0] + "~" + range[1] + " ");
}
System.out.println();
}
}
}
输出结果如下:
出现0次的范围:
0~53 95~192 234~301 343~348 390~452 494~531 603~670 712~774 816~818 860~927 999~999
出现1次的范围:
54~94 193~233 302~342 349~389 453~493 532~561 573~602 775~815 819~859 928~930 972~998
出现2次的范围:
562~572 671~711 931~957 969~971
出现3次的范围:
958~968