今天在群里又有一个朋友问到了这样一个练习,我索性将代码贴到这里,下次需要的朋友可以来这里看。
用到知识点:数组、集合、IO流
问题描述:在如下图所示的一个txt文件中读取数据到内存,然后统计列除过0的各个数字的个数(放入Map)并按照列的数据大小排序。
代码:
package com.test; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.TreeMap; public class Week { private static List<int[]> readFile1(String fileName) { List<int[]> list = new ArrayList<int[]>(); String line = ""; int[] arr; FileReader fr = null; BufferedReader br = null; try { File file = new File(fileName); fr = new FileReader(file); br = new BufferedReader(fr); while (br.ready()) { line = br.readLine(); String[] data = line.split(","); arr = new int[data.length]; for (int j = 0; j < data.length; j++) { arr[j] = Integer.parseInt(data[j]); } list.add(arr); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally{ if(br != null){ try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if(fr != null){ try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } } return list; } private static int[][] revertData(List<int[]> data) { int maxCol = 0; for (int i = 0; i < data.size(); i++) { if (data.get(i).length > maxCol) { maxCol = data.get(i).length; } } int[][] arrs = new int[maxCol][data.size()]; for (int i = 0; i < data.size(); i++) { int[] arr = data.get(i); for (int j = 0; j < arr.length; j++) { arrs[j][i] = arr[j]; } } return arrs; } private static void countKeyNum(int[][] arrs) { TreeMap<Integer, Integer> map; for (int i = 0; i < arrs.length; i++) { map = new TreeMap<Integer, Integer>(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o1.compareTo(o2); } }); for (int j = 0; j < arrs[i].length; j++) { if (arrs[i][j] == 0) continue; if (map.containsKey(arrs[i][j])) { map.put(arrs[i][j], map.get(arrs[i][j]) + 1); } else { map.put(arrs[i][j], 1); } } System.out.println(map); } } public static void main(String args[]) { List<int[]> data = readFile1("week.txt"); int[][] arrs = revertData(data); countKeyNum(arrs); } }部分运行结果:
开源java内容管理 j4cms域名申请下来了,布布扣,bubuko.com
原文地址:http://blog.csdn.net/sdjn_jiangxiaobei/article/details/30078039