就是有一个文件,里面有一些数字,咋用代码把这些数字按照10到20,20到30这样分段给他分出来 分段列出来,20到30都有多少30到40都有多少
你先把文件中的数取出来放集合或者数组中,然后再去遍历判断。
先把文件内容贴出来看看,是什么样子的格式。
您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~
如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~
ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632
读取文件,用文件流或bufferReader去读
分段的代码如下
public static void main(String args[]) {
BufferedReader br = null;
try{
br = new BufferedReader(new FileReader("路径"));
String content = br.readLine();
String[] numStr = content.split(" ");
List<Integer> numList = new ArrayList<>();
for (String str : numStr) {
if (!StringUtils.isEmpty(str)) {
numList.add(Integer.parseInt(str));
}
}
Map<Integer, List<Integer>> map = new HashMap<>();
for (Integer num : numList) {
map.computeIfAbsent(num / 10, e -> new ArrayList<>()).add(num);
}
for (Integer num : map.keySet()) {
System.out.println((num * 10) + "-" + ((num + 1) * 10) + ":" + map.get(num).toString());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try{
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
1.读取空格分割的文件
String filePath="文件路径";
StringBuffer sbf = new StringBuffer();
try (InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "utf-8"); BufferedReader reader = new BufferedReader(isr)) {
String tempStr;
while ((tempStr = reader.readLine()) != null) {
sbf.append(tempStr.trim()).append(" ");
}
} catch (Exception e) {
e.printStackTrace();
}
2.分割数字,key值为数字所在范围,如0~10、10~20、100~110、1000~1010等,左闭右开,每个key对应的list为在该范围内的数字
Map<String, List<Double>> map = Stream.of(sbf.toString().split("\\s+")).map(Double::new).collect(Collectors.groupingBy(value -> {
int number = value.intValue() / 10;
return number * 10 + "~" + (number * 10 + 10);
}, () -> new TreeMap(Comparator.comparing((String data) -> Integer.parseInt(data.split("~")[0]))), Collectors.toList()));
其中:
(1)按空格分割
sbf.toString().split("\\s+")
(2)转为double
map(Double::new)
(3)数字转为范围,如5会转为0~10
value -> {
int number = value.intValue() / 10;
return number * 10 + "~" + (number * 10 + 10);
}
(4)范围从小到大排序即key的排序
() -> new TreeMap(Comparator.comparing((String data) -> Integer.parseInt(data.split("~")[0])))